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.
The 60-second answer
Section titled “The 60-second answer”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
nilandfalseare falsy —0and""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.
Objects, variables and references
Section titled “Objects, variables and references”a = "hello"b = ab << " world"a # => "hello world" — a and b point at the same objecta.object_id == b.object_id # => truea = a + "!" # rebinding a to a NEW object; b unchangedAssignment 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.
Truthiness
Section titled “Truthiness”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.
Symbols vs strings
Section titled “Symbols vs strings”: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? # => falseUse 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.
Methods
Section titled “Methods”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;
returnis 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.
Enumerables
Section titled “Enumerables”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(:+) # => 15nums.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.
Destructuring and safe navigation
Section titled “Destructuring and safe navigation”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 matchuser&.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.
Follow-up questions
Section titled “Follow-up questions”- Why is
0truthy in Ruby, and what bug does that cause in ported code? - When would you choose a symbol over a string as a hash key?
- What is the difference between
mapandeach, and when iseachthe right choice? - How does Ruby 3 keyword separation change the way you write APIs?
- What does
freezedo, and why do files use# frozen_string_literal: true?
Common traps
Section titled “Common traps”if valuedoes not check emptiness. Usevalue.nil?or.empty?.- Mutating a string argument in place. Callers do not expect it; use
dup. Hash#[]returningnilwhen you expected a default. UseHash.new(0)orfetch.and/orin a value expression.x = true and falseassignstrue.- Treating
!as “returns boolean”.map!mutates;save!raises.