Skip to content

Ruby Basics

Ruby’s basics look familiar until they do not. Four facts explain most of it: only nil and false are falsy, symbols are not strings, assignment returns its value, and every operation is a message send.

In Ruby everything is an object and every operation is a message send. Variables are references, not boxes; untyped variables pointing at typed objects. Five kinds: local, instance, class, global, constant. Only nil and false are falsy — 0 and "" are truthy. Symbols are immutable interned identifiers; strings are mutable. Methods return their last expression, and ?/!/= suffixes are conventions. Enumerables are the workhorse: each, map, select, reduce.

a = "hello"
b = a
b << " world"
a # => "hello world" — a and b point at the same object
a.object_id == b.object_id # => true
a = a + "!" # rebinding a to a NEW object; b unchanged

Assignment never copies. dup, clone, + and * create new objects.

Kind Sigil Scope Lifetime
Local name Current method/block Until the scope ends
Instance @name One object As long as the object lives
Class @@name Class and subclasses Process lifetime
Global $name Everywhere Process lifetime
Constant NAME Lexical scope Process lifetime

Class variables are shared with subclasses, which is why they are usually a smell.

Only nil and false are falsy. Everything else — 0, "", [], {} — is truthy, so [0, "", []].map { |v| v ? :t : :f } is [:t, :t, :t].

This is the biggest source of bugs for developers arriving from Python or JavaScript: if param does not check for emptiness, it checks for non-nil. &&, ||, ! and the keyword forms and, or, not differ only in precedence — && binds tighter than =, and binds looser.

:a.object_id == :a.object_id # => true — interned
"a".object_id == "a".object_id # => false — a new object each time
:a.frozen? # => true
"a".frozen? # => false

Use symbols for names — hash keys, method names, keyword arguments, enum-like states. Use strings for data — user input, displayed text, anything mutated. Symbols are garbage collected in modern Ruby, but "user_input".to_sym on unbounded input is still a DoS vector.

def greet(name, punctuation: "!")
"Hello, #{name}#{punctuation}"
end
greet("Ada") # => "Hello, Ada!"
greet("Ada", punctuation: "?") # => "Hello, Ada?"
def request(url, retries: 3, **options, &handler)
[url, retries, options, handler&.call]
end
request("https://x", timeout: 5) { :done } # => ["https://x", 3, {timeout: 5}, :done]
  • The last expression is returned; return is only for early exit.
  • ? means “returns a boolean”, ! means “dangerous” — mutating (sort!) or raising (save!).
  • Ruby 3 separates positional and keyword arguments: a hash no longer auto-converts; use **hash.
  • Parentheses are optional, which enables DSLs and ambiguity. Use them for multi-argument calls.

Enumerable is mixed into Array, Hash, Range, Set, and everything is built on each.

nums = [1, 2, 3, 4, 5]
nums.map { |n| n * 2 } # => [2, 4, 6, 8, 10]
nums.select(&:even?) # => [2, 4]
nums.reduce(:+) # => 15
nums.each_slice(2).to_a # => [[1, 2], [3, 4], [5]]
nums.partition(&:even?) # => [[2, 4], [1, 3, 5]]
nums.group_by(&:odd?) # => {true=>[1, 3, 5], false=>[2, 4]}
nums.each_with_object({}) { |n, h| h[n] = n**2 }

each returns the receiver, map and select return new arrays, and Hash#each yields [key, value] pairs that destructure in the block parameters.

a, *rest = [1, 2, 3] # a=1, rest=[2, 3]
first, (second, third) = [1, [2, 3]]
{ "a" => 1 }.each { |key, value| } # block params destructure pairs
def min_max(list) = [list.min, list.max]
low, high = min_max([3, 1])
[1, 2] => [x, y] # Ruby 3 pattern matching, raises if no match
user&.profile&.name # nil if any link is nil

&. only guards against nil. It does not guard against a missing method, and overusing it hides the fact that your data model allows nils where it should not.

  1. Why is 0 truthy in Ruby, and what bug does that cause in ported code?
  2. When would you choose a symbol over a string as a hash key?
  3. What is the difference between map and each, and when is each the right choice?
  4. How does Ruby 3 keyword separation change the way you write APIs?
  5. What does freeze do, and why do files use # frozen_string_literal: true?
  • if value does not check emptiness. Use value.nil? or .empty?.
  • Mutating a string argument in place. Callers do not expect it; use dup.
  • Hash#[] returning nil when you expected a default. Use Hash.new(0) or fetch.
  • and/or in a value expression. x = true and false assigns true.
  • Treating ! as “returns boolean”. map! mutates; save! raises.