Common pitfalls
suggest changeRuby is designed to be pleasant to write, but some of its conveniences surprise programmers coming from other languages, and even experienced Rubyists get bitten now and then. This article collects the mistakes that show up most often in real code, shows what goes wrong, and gives the fix.
All examples were run with Ruby 4.0.
Shared mutable default objects
Array.new(size, obj) and Hash.new(obj) don't copy obj. Every slot gets the same object:
grid = Array.new(3, [])
grid[0] << "x"
p grid
p grid.map(&:object_id).uniq.size
grid = Array.new(3) { [] }
grid[0] << "x"
p grid
[["x"], ["x"], ["x"]]
1
[["x"], [], []]
The block form runs once per element, so each row is a new array.
Hash.new([]) is even worse. The default value is returned for missing keys, but it is never stored in the hash. << mutates the one shared default array, and the hash stays empty:
groups = Hash.new([])
groups[:fruit] << "apple"
groups[:veg] << "carrot"
p groups
p groups[:anything]
groups = Hash.new { |hash, key| hash[key] = [] }
groups[:fruit] << "apple"
groups[:veg] << "carrot"
p groups
{}
["apple", "carrot"]
{fruit: ["apple"], veg: ["carrot"]}
Use the block form, and make sure the block assigns hash[key] = .... See Setting Default Values for more.
Only nil and false are falsy
In Ruby, 0, "", [] and {} are all true. Code ported from Python, JavaScript or PHP often relies on empty values being false:
def describe(value)
value ? "truthy" : "falsy"
end
[0, "", [], {}, "false", nil, false].each do |v|
puts "#{v.inspect.ljust(7)} #{describe(v)}"
end
items = []
puts "has items" if items # always true
puts "has items" unless items.empty?
puts "really has items" if items.any?
0 truthy
"" truthy
[] truthy
{} truthy
"false" truthy
nil falsy
false falsy
has items
Check emptiness explicitly with empty?, any? or zero?. See Truthiness.
and / or are not && / ||
and and or have lower precedence than =, so they don't do what they look like in an assignment:
result = true and false
p result
result = (true and false)
p result
result = true && false
p result
true
false
false
The first line is parsed as (result = true) and false. Ruby doesn't even warn about it, with or without -w.
Use &&, || and ! for boolean logic. Reserve and / or for control flow, such as save or raise "save failed", if you use them at all.
Integer division and floating point
Dividing two integers gives an integer, rounded toward negative infinity:
p 7 / 2
p -7 / 2
p 7.0 / 2
p 7.fdiv(2)
p 7 / 2.0
3
-4
3.5
3.5
3.5
Note that -7 / 2 is -4, not -3 as in C or Java. To get a float, make one of the operands a float or use fdiv.
Floats are binary IEEE 754 numbers, so most decimal fractions can't be represented exactly:
p 0.1 + 0.2
p 0.1 + 0.2 == 0.3
p (0.1 + 0.2 - 0.3).abs < Float::EPSILON
require "bigdecimal"
p BigDecimal("0.1") + BigDecimal("0.2") == BigDecimal("0.3")
p 0.1r + 0.2r == 0.3r
0.30000000000000004
false
true
true
true
Never compare floats with ==. For money, use BigDecimal (constructed from a string, not a float), rationals (0.1r), or integer cents.
Methods that mutate their arguments
Ruby passes references to objects. A method that calls a mutating method (<<, upcase!, concat, push, merge!...) on its argument changes the caller's object:
def shout(text)
text << "!"
text.upcase!
text
end
greeting = +"hello"
loud = shout(greeting)
p loud
p greeting
p loud.equal?(greeting)
def shout_safely(text)
text.upcase + "!"
end
greeting = "hello"
p shout_safely(greeting)
p greeting
"HELLO!"
"HELLO!"
true
"HELLO!"
"hello"
Unless mutating the argument is the documented purpose of a method, use the non-bang versions that return new objects (upcase, +, merge).
A related trap: string literals are not frozen by default yet, but Ruby is moving there. Mutating a literal works today, and prints a warning when deprecation warnings are on:
s = "hello"
s << " world"
p s
$ ruby -W:deprecated mutate.rb
mutate.rb:2: warning: literal string will be frozen in the future (run with --debug-frozen-string-literal for more information)
"hello world"
Add the # frozen_string_literal: true magic comment to new files, and use +"..." (or String.new) when you really need a mutable string:
# frozen_string_literal: true
s = "hello"
begin
s << " world"
rescue FrozenError => e
puts "#{e.class}: #{e.message}"
end
t = +"hello"
t << " world"
p t
FrozenError: can't modify frozen String: "hello"
"hello world"
Calling a setter without self
Inside a method, name = value always creates a local variable. It never calls the name= setter:
class Counter
attr_accessor :count
def initialize
@count = 0
end
def increment_wrong
count = count + 1
end
def increment
self.count += 1
end
end
c = Counter.new
begin
c.increment_wrong
rescue NoMethodError => e
puts "#{e.class}: #{e.message}"
end
p c.count
c.increment
p c.count
NoMethodError: undefined method '+' for nil
0
1
In increment_wrong, the parser sees count = and makes count a local variable for the rest of the method, so the count on the right side is that (still nil) local, not the getter. Here it at least crashes; with count = 5 the assignment would silently do nothing useful. Write self.count = ... or assign @count directly.
Misspelled instance variables are silently nil
Reading an instance variable that was never assigned returns nil. Since Ruby 3.0 there's no warning, even with -w:
class Person
def initialize(name)
@name = name
end
def greet
"Hello, #{@nmae}"
end
end
p Person.new("Ann").greet
"Hello, "
Accessing state through attr_reader methods instead of raw @ivars turns a typo into a NameError, and tests that check actual output catch the rest.
= instead of == in a condition
An assignment is an expression, so it's legal in an if:
status = :draft
if status = :published
puts "status is now #{status.inspect}"
end
cond.rb:2: warning: found '= literal' in conditional, should be ==
status is now :published
Ruby warns only when the right side is a literal. With if status = compute_status there's no warning at all. If you assign in a condition on purpose (if (m = re.match(line))), wrap it in parentheses to signal intent.
{ } and do ... end bind differently
Braces bind to the nearest method call; do ... end binds to the outermost one. With a method like p or puts that takes arguments without parentheses, this changes the meaning:
numbers = [1, 2, 3]
p numbers.map { |n| n * 2 }
p numbers.map do |n|
n * 2
end
result = numbers.map do |n|
n * 2
end
p result
[2, 4, 6]
#<Enumerator: [1, 2, 3]:map>
[2, 4, 6]
In the second call, the do block is passed to p (which ignores it), and map without a block returns an enumerator. The usual convention is braces for one-line blocks whose value you use, and do ... end for multi-line blocks.
Modifying a collection while iterating over it
Removing elements from an array inside each makes the iterator skip elements:
numbers = [2, 4, 6, 7]
numbers.each { |n| numbers.delete(n) if n.even? }
p numbers
numbers = [2, 4, 6, 7]
numbers.reject!(&:even?)
p numbers
[4, 7]
[7]
After 2 is deleted, 4 moves to index 0, but the iterator moves on to index 1. Use reject!, select!, delete_if, or build a new collection with reject / select.
Hashes refuse to grow during iteration:
h = { a: 1, b: 2 }
begin
h.each { |k, v| h[:"#{k}2"] = v }
rescue => e
puts "#{e.class}: #{e.message}"
end
RuntimeError: can't add a new key into hash during iteration
Hash key surprises
Hash lookup uses eql? and hash, not ==. That means 1 and 1.0 are different keys even though they are ==:
prices = { 1 => "one" }
p prices[1.0]
p 1 == 1.0
p 1.eql?(1.0)
nil
true
false
Mutating an object after using it as a key breaks lookup, because the hash stored the key under its old hash code:
key = [1, 2]
h = { key => "pair" }
key << 3
p h[[1, 2, 3]]
p h[[1, 2]]
h.rehash
p h[[1, 2, 3]]
nil
nil
"pair"
String keys are the exception: Hash#[]= stores a frozen copy of an unfrozen string key, so mutating the original string later doesn't affect the hash.
The most common hash bug, though, is mixing symbol and string keys. "name" and :name are different keys, and parsed JSON uses strings:
require "json"
data = JSON.parse('{"name": "Ann", "age": 31}')
p data[:name]
p data["name"]
data = JSON.parse('{"name": "Ann", "age": 31}', symbolize_names: true)
p data[:name]
nil
"Ann"
"Ann"
Pick one convention at the boundary of your program (for example symbolize_names: true) and stick with it. Using fetch instead of [] makes a wrong key fail loudly with KeyError.
Default equality is identity
Unless you define ==, two objects with the same contents are not equal, and they won't work as hash keys or with include?:
class Point
attr_reader :x, :y
def initialize(x, y)
@x, @y = x, y
end
end
a = Point.new(1, 2)
b = Point.new(1, 2)
p a == b
p [a].include?(b)
p({ a => 1 }[b])
Point2 = Data.define(:x, :y)
p Point2.new(x: 1, y: 2) == Point2.new(x: 1, y: 2)
p({ Point2.new(x: 1, y: 2) => 1 }[Point2.new(x: 1, y: 2)])
false
false
nil
true
1
For value objects, use Data.define or Struct, which define ==, eql? and hash for you. If you write a class by hand, define all three consistently (see Overriding hash function).
Class variables are shared with subclasses
A @@class_variable is shared by the class and all of its subclasses. Assigning it in a subclass overwrites the parent's value:
class Base
@@registry = []
def self.register(item)
@@registry << item
end
def self.registry = @@registry
end
class Plugin < Base
@@registry = [:plugin_only]
end
Base.register(:core)
p Base.registry
p Plugin.registry
[:plugin_only, :core]
[:plugin_only, :core]
Usually you want per-class state, which is what class-level instance variables give you:
class Base2
@registry = []
class << self
attr_reader :registry
def inherited(sub)
super
sub.instance_variable_set(:@registry, [])
end
end
end
class Plugin2 < Base2; end
Base2.registry << :core
Plugin2.registry << :plugin
p Base2.registry
p Plugin2.registry
[:core]
[:plugin]
See Class Variables for details.
||= overwrites false
a ||= b means a || a = b, so it assigns when the current value is nil or false. That breaks boolean settings:
settings = { cache: false }
settings[:cache] ||= true
p settings[:cache]
settings = { cache: false }
settings[:cache] = true unless settings.key?(:cache)
p settings[:cache]
settings = { cache: false }
p settings.fetch(:cache) { true }
true
false
false
The same applies to memoization: @result ||= expensive_call recomputes every time if the result is nil or false. Use defined?(@result) or instance_variable_defined? to memoize falsy values.
Forgetting what a method returns
A method returns the value of its last expression. Two frequent surprises are each, which returns the receiver rather than the block results, and puts, which returns nil:
def total(items)
items.each { |i| i * 2 }
end
p total([1, 2, 3])
def log_and_return(x)
puts "got #{x}"
end
p log_and_return(5)
[1, 2, 3]
got 5
nil
Use map when you want the transformed values, and make sure a debug puts isn't the last line of a method whose value matters.
return inside a proc
return in a block or proc returns from the method that defined the block, not from the block. In a lambda it returns from the lambda only:
def call_proc
pr = proc { return 10 }
pr.call
20
end
def call_lambda
la = -> { return 10 }
la.call
20
end
p call_proc
p call_lambda
def make_proc
proc { return 1 }
end
begin
make_proc.call
rescue LocalJumpError => e
puts "#{e.class}: #{e.message}"
end
10
20
LocalJumpError: unexpected return
If the defining method has already returned, there's nowhere to return to and you get LocalJumpError. Use next value to return a value from a block, and lambdas when you need function-like behavior. See Blocks and procs and lambdas.
Lenient string to number conversion
to_i and to_f never fail. They parse as much as they can and return 0 for garbage:
p "42abc".to_i
p "abc".to_i
p "".to_f
p "0x1A".to_i
p Integer("0x1A")
begin
Integer("abc")
rescue ArgumentError => e
puts "#{e.class}: #{e.message}"
end
p Integer("abc", exception: false)
p Integer("010")
p Integer("010", 10)
42
0
0.0
0
26
ArgumentError: invalid value for Integer(): "abc"
nil
8
10
For user input, use Integer() and Float(), which raise on invalid input. Watch out for the leading-zero rule: Integer("010") is octal 8. Pass base 10 when parsing things like zero-padded IDs.
freeze is shallow, and readers leak internals
freeze prevents changes to the object itself, not to the objects it references. Similarly, attr_reader returns the actual internal object, which callers can mutate:
class Config
attr_reader :tags
def initialize
@tags = ["prod"]
end
end
c = Config.new
c.tags << "hacked"
p c.tags
DEFAULTS = { retries: 3, hosts: ["a", "b"] }.freeze
begin
DEFAULTS[:retries] = 5
rescue FrozenError => e
puts "#{e.class}: #{e.message}"
end
DEFAULTS[:hosts] << "c"
p DEFAULTS
["prod", "hacked"]
FrozenError: can't modify frozen Hash: {retries: 3, hosts: ["a", "b"]}
{retries: 3, hosts: ["a", "b", "c"]}
Freeze nested values too (hosts: ["a", "b"].freeze), or return copies (@tags.dup) or frozen views from readers. Also remember that constants can be reassigned with only a warning; see Immutability.
Bare super passes all arguments
super without parentheses forwards every argument the current method received. If the parent takes fewer arguments, it fails:
class Animal
def initialize(name)
@name = name
end
end
class Dog < Animal
def initialize(name, breed)
super
@breed = breed
end
end
begin
Dog.new("Rex", "lab")
rescue ArgumentError => e
puts "#{e.class}: #{e.message}"
end
class Cat < Animal
def initialize(name, indoor)
super(name)
@indoor = indoor
end
end
p Cat.new("Tom", true).instance_variables
ArgumentError: wrong number of arguments (given 2, expected 1)
[:@name, :@indoor]
Use super(args) to pass specific arguments and super() to pass none.
Passing a hash where keywords are expected
Since Ruby 3.0, a hash is no longer automatically converted to keyword arguments:
def connect(host, port: 80, tls: false)
"#{host}:#{port} tls=#{tls}"
end
opts = { port: 443, tls: true }
p connect("example.com", **opts)
begin
connect("example.com", opts)
rescue ArgumentError => e
puts "#{e.class}: #{e.message}"
end
begin
connect("example.com", prot: 8080)
rescue ArgumentError => e
puts "#{e.class}: #{e.message}"
end
"example.com:443 tls=true"
ArgumentError: wrong number of arguments (given 2, expected 1)
ArgumentError: unknown keyword: :prot
Use **opts to splat a hash into keywords. The upside of real keyword arguments is the last error: a typo in a keyword name fails immediately, while a misspelled key in an options = {} hash is silently ignored. See Keyword Arguments.
Rescuing too much (or too little)
A bare rescue catches every StandardError, including NoMethodError caused by typos in your own code:
def parse(s)
Integer(s)
rescue
0
end
p parse("oops")
def lookup(h)
h.fecth(:a)
rescue
nil
end
p lookup({ a: 1 })
def parse_strict(s)
Integer(s)
rescue ArgumentError, TypeError
0
end
p parse_strict("oops")
p parse_strict(nil)
0
nil
0
0
lookup has a typo (fecth) and will always return nil without any hint of the bug. Always name the exception classes you expect.
The opposite mistake is rescue Exception, which also catches Interrupt (Ctrl+C), SystemExit and NoMemoryError, making a program hard to stop. And some errors that look ordinary aren't StandardError at all: NotImplementedError is a ScriptError, so rescue => e does not catch it:
def fetch_data
raise NotImplementedError, "TODO"
end
begin
fetch_data
rescue => e
puts "rescued #{e.class}"
end
todo.rb:2:in 'Object#fetch_data': TODO (NotImplementedError)
from todo.rb:6:in '<main>'
See Handling multiple exceptions and Exceptions.
Catching pitfalls early
Many of these mistakes can be caught by tools before they reach production:
- Run with warnings on (
ruby -w, orRUBYOPT="-W"in tests) to catch=in conditions, deprecated mutation of string literals and unused variables. - Add
# frozen_string_literal: trueto every file so accidental string mutation raises instead of silently changing shared data. - Use RuboCop. Its default cops flag
and/orin conditions, barerescue,rescue Exception,Hash.new([])-style shared defaults, class variables and ambiguous block usage. - Prefer strict methods (
fetch,Integer(), keyword arguments) that fail loudly over lenient ones that returnnilor0.