New collection methods in Ruby 3
suggest changeEvery Ruby release since 3.0 has added a few small methods to Array, Hash, Enumerable and Enumerator. None of them is big enough to get much attention on its own, but together they replace a lot of hand-written helpers and awkward idioms:
params = {name: "Ada", password: "secret"}
p params.except(:password) # 3.0
p ["ada", "grace"].intersect?(["grace"]) # 3.1
p [1, nil, 2].each.compact # 3.1
p Enumerator.product([1, 2], [:a, :b]).to_a # 3.2
p 95.ceildiv(20) # 3.2
p [10, 20, 30].fetch_values(0, 2) # 3.4
p [1, 2, 3, 4].rfind(&:odd?) # 4.0
{name: "Ada"}
true
[1, 2]
[[1, :a], [1, :b], [2, :a], [2, :b]]
5
[10, 30]
3
This article goes through them in order of the version that added them, with the edge cases worth knowing. All examples were run with Ruby 4.0. If you have to support older Rubies, check the version next to each heading. For the basics of the modules involved see Enumerable in Ruby and Enumerators.
Hash#except (Ruby 3.0)
Hash#except returns a copy of the hash without the given keys. It's the opposite of slice, which keeps only the given keys. Rails has had it for years through ActiveSupport, and Ruby 3.0 made it part of core:
params = {name: "Ada", email: "ada@example.com", password: "secret", admin: true}
p params.except(:password, :admin)
p params.except(:missing)
p params.slice(:name, :email) # the opposite: keep only these keys
p params # the receiver is unchanged
{name: "Ada", email: "ada@example.com"}
{name: "Ada", email: "ada@example.com", password: "secret", admin: true}
{name: "Ada", email: "ada@example.com"}
{name: "Ada", email: "ada@example.com", password: "secret", admin: true}
Keys that aren't in the hash are silently ignored. Before 3.0 you would write params.reject { |k, _| [:password, :admin].include?(k) } (see Filtering hashes), or dup the hash and call delete for every key.
A typical use is removing sensitive values before logging:
def log_request(headers)
safe = headers.except("Authorization", "Cookie")
safe.each { |k, v| puts "#{k}: #{v}" }
end
log_request(
"Host" => "example.com",
"Authorization" => "Bearer abc123",
"Cookie" => "session=xyz",
"Accept" => "text/html"
)
Host: example.com
Accept: text/html
One thing to be aware of: like select, reject and slice, except returns a plain hash. A default value or default proc of the original is not copied:
counts = Hash.new(0)
counts[:a] += 1
p counts.except(:b)[:zzz]
p counts.dup[:zzz]
cache = Hash.new { |h, k| h[k] = k.to_s * 2 }
p cache.except(:x)[:y]
nil
0
nil
If the result must keep counting with += 1, use dup followed by delete, or set the default again with default=.
Hash#transform_keys with a mapping (Ruby 3.0)
transform_keys (2.5) used to take only a block. Since 3.0 it also accepts a hash that maps old keys to new ones. Keys that aren't in the mapping are left alone, or passed to the block if you give one:
row = {"First Name" => "Ada", "Last Name" => "Lovelace", "Born" => 1815}
p row.transform_keys("First Name" => :first, "Last Name" => :last)
p row.transform_keys({"First Name" => :first}) { _1.downcase.to_sym }
{first: "Ada", last: "Lovelace", "Born" => 1815}
{first: "Ada", "last name": "Lovelace", born: 1815}
This is handy for renaming columns of a CSV row or fields of a JSON object.
Array#intersect? (Ruby 3.1)
intersect? answers "do these two arrays have at least one element in common?":
admins = ["ada", "grace"]
online = ["linus", "grace", "guido"]
p admins.intersect?(online)
p admins.intersect?(["linus"])
p (admins & online).any? # the pre-3.1 way: builds a temporary array
p admins.intersect?([])
true
false
true
false
The old idiom (a & b).any? builds the whole intersection only to throw it away. intersect? stops as soon as it finds a common element. It has another advantage: (a & b).any? gives the wrong answer when the only common element is nil or false, because any? without a block checks for truthy elements. [nil].intersect?([nil]) is true.
Elements are compared with hash and eql?, the same as & (see Arrays union intersection and difference). That means 1.0 and 1 don't match, while nested arrays with equal contents do. The argument must be an array; Set has its own intersect?, which accepts any enumerable:
p [1, 2, 3].intersect?(Set[3, 4]) rescue p $!
p Set[1, 2, 3].intersect?([3, 4])
p [1.0].intersect?([1])
p [[1, 2]].intersect?([[1, 2]])
#<TypeError: no implicit conversion of Set into Array>
true
false
true
More on sets in Sets.
Enumerable#compact and Lazy#compact (Ruby 3.1)
Array#compact and Hash#compact have been around for a long time. Ruby 3.1 added compact to Enumerable, so it works on any enumerable, and to Enumerator::Lazy. The Enumerable version always returns an array:
p Set[1, nil, 2].compact
emails = Struct.new(:rows) do
include Enumerable
def each(&) = rows.each(&)
end.new(["a@x.io", nil, "b@x.io", nil])
p emails.compact
p emails.compact.class
[1, 2]
["a@x.io", "b@x.io"]
Array
The lazy version is the more useful of the two. It drops nils from a lazy pipeline without forcing it, which pairs well with methods that return nil on failure, like Integer(str, exception: false):
lines = ["42", "", "x", "7", "13", "nope"]
nums = lines.lazy.map { Integer(_1, exception: false) }.compact
p nums
p nums.first(2)
#<Enumerator::Lazy: #<Enumerator::Lazy: #<Enumerator::Lazy: ["42", "", "x", "7", "13", "nope"]>:map>:compact>
[42, 7]
In this case filter_map (2.7) would do the job in one step, but compact is the right tool when the nils come from somewhere else, for example from an enumerator that reads records from a file.
Enumerable#tally with an accumulator hash (Ruby 3.1)
tally (2.7) counts how many times each element occurs. Since 3.1 it takes an optional hash and adds the counts to it instead of creating a new one. That lets you count across several collections without merging intermediate hashes:
totals = {}
["red", "blue", "red"].tally(totals)
["blue", "green"].tally(totals)
p totals
totals = {"red" => 10}
%w[red red].tally(totals)
p totals
{"red" => 2, "blue" => 2, "green" => 1}
{"red" => 12}
Existing counts are incremented, so you can start from earlier results. A word count over several files looks like this:
def words(path) = File.foreach(path).flat_map { _1.downcase.scan(/[a-z']+/) }
File.write("a.txt", "the cat sat on the mat\n")
File.write("b.txt", "The dog sat\nthe end\n")
freq = {}
%w[a.txt b.txt].each { |f| words(f).tally(freq) }
p freq.max_by(3) { |_, n| n }
[["the", 4], ["sat", 2], ["on", 1]]
The hash must be mutable and every existing value must be an integer:
p (%w[a].tally({}.freeze) rescue $!)
p (%w[a].tally({"a" => "x"}) rescue $!)
#<FrozenError: can't modify frozen Hash: {}>
#<TypeError: wrong argument type String (expected Integer)>
There is no tally_by. Use map first, or group_by followed by transform_values(&:size).
each_cons and each_slice return self (Ruby 3.1)
With a block, each_cons and each_slice used to return nil. Since 3.1 they return the receiver, like each does:
r = [1, 2, 3, 4, 5].each_slice(2) { |pair| p pair }
p r
r = [1, 2, 3, 4].each_cons(2) { |a, b| print b - a, " " }
puts
p r
[1, 2]
[3, 4]
[5]
[1, 2, 3, 4, 5]
1 1 1
[1, 2, 3, 4]
It's a small change, but it means you can keep chaining after them:
temps = [12, 15, 11, 18, 21]
temps
.each_cons(2) { |a, b| puts "#{a} -> #{b}: #{b > a ? 'up' : 'down'}" }
.then { puts "max #{_1.max}" }
12 -> 15: up
15 -> 11: down
11 -> 18: up
18 -> 21: up
max 21
Without a block, both still return an enumerator, as before.
Enumerator::Lazy#eager (Ruby 3.1)
A lazy enumerator stays lazy through map, select and friends. That's what you want inside a pipeline, but it can surprise callers that get a lazy enumerator back from a method and call map on it, expecting an array. eager turns a lazy enumerator into a normal (non-lazy) enumerator without evaluating it:
lazy = [1, 2, 3].lazy.select(&:odd?)
p lazy.map { _1 * 10 }
p lazy.eager.map { _1 * 10 }
#<Enumerator::Lazy: #<Enumerator::Lazy: #<Enumerator::Lazy: [1, 2, 3]>:select>:map>
[10, 30]
Use it at the boundary of a method that is lazy internally:
def active_emails(users)
users.lazy.select { _1[:active] }.map { _1[:email] }.eager
end
users = [
{email: "a@x.io", active: true},
{email: "b@x.io", active: false},
{email: "c@x.io", active: true},
]
emails = active_emails(users)
p emails.class
p emails.sort # Enumerable methods are eager again
p emails.first(1)
Enumerator
["a@x.io", "c@x.io"]
["a@x.io"]
The work is still done only when someone iterates the result, and first(1) stops early. Before 3.1 the only way out of laziness was force (or to_a), which evaluates everything immediately and can't work with infinite sources.
Enumerator.product (Ruby 3.2)
Enumerator.product builds the Cartesian product of any number of enumerables. Unlike Array#product, it doesn't build all combinations in memory; it returns an Enumerator::Product that yields them one by one:
sizes = %w[S M L]
colors = %w[red blue]
e = Enumerator.product(sizes, colors)
p e
p e.size
p e.to_a
Enumerator.product(1..2, [:x, :y], [true]) { |n, sym, flag| p [n, sym, flag] }
#<Enumerator::Product: [["S", "M", "L"], ["red", "blue"]]>
6
[["S", "red"], ["S", "blue"], ["M", "red"], ["M", "blue"], ["L", "red"], ["L", "blue"]]
[1, :x, true]
[1, :y, true]
[2, :x, true]
[2, :y, true]
The last enumerable changes fastest, like nested loops with the first argument as the outermost loop. With a block, the combinations are passed to the block directly.
Because nothing is materialized, it works for large spaces, combined with lazy for early exit:
grid = Enumerator.product(0..999, 0..999)
p grid.size
p grid.lazy.select { |x, y| x * y == 391 && x <= y }.first(2)
p Enumerator.product(1.., [:a]).take(3)
p Enumerator.product(1.., [:a]).size
p Enumerator.product.to_a
1000000
[[1, 391], [17, 23]]
[[1, :a], [2, :a], [3, :a]]
Infinity
[[]]
[*0..999].product([*0..999]) would allocate a million two-element arrays before you could look at the first one. The first argument may even be infinite, as long as the others are finite, because it's the outer loop. With no arguments the product has exactly one combination, the empty one.
Integer#ceildiv (Ruby 3.2)
ceildiv is integer division that rounds up instead of down. The classic use is counting pages or batches:
def pages(total_items, per_page) = total_items.ceildiv(per_page)
p pages(95, 20)
p pages(100, 20)
p pages(0, 20)
5
5
0
It is correct for negative numbers too, and it replaces several error-prone idioms:
p 10.ceildiv(3)
p 9.ceildiv(3)
p -10.ceildiv(3)
p 10.ceildiv(-3)
# older ways
p (10 / 3.0).ceil # goes through Float
p -(-10 / 3) # negate, floor-divide, negate
p (10 + -3 - 1) / -3 # (a + b - 1) / b is wrong for negative b
4
3
-3
-3
4
4
-2
The float version looks fine for small numbers but loses precision for large integers, because a Float only has 53 bits of mantissa:
big = 10**30 + 1
p big.ceildiv(10**15)
p (big / 10.0**15).ceil # float rounding error
1000000000000001
1000000000000000
ceildiv stays in integer arithmetic, so it's exact for any size of Integer. It's defined only on Integer, not on Float or Rational.
Hash.new(capacity:) (Ruby 3.4)
When you know roughly how many entries a hash will get, Hash.new(capacity: n) allocates room for them up front, so the hash doesn't have to grow and rehash several times while you fill it. It combines with a default value or a default block:
h = Hash.new(capacity: 1000)
p h, h.size
p h[:x]
with_default = Hash.new(0, capacity: 10)
p with_default[:x]
with_block = Hash.new(capacity: 10) { |hash, k| hash[k] = [] }
with_block[:a] << 1
p with_block
{}
0
nil
0
{a: [1]}
The capacity is only a hint: the hash is still empty and grows past it when needed. Don't expect miracles from it. Filling a hash with 2 million integers was only a bit faster with the right capacity on this machine:
require "benchmark"
N = 2_000_000
Benchmark.bm(10) do |x|
x.report("default") { h = {}; N.times { h[_1] = _1 } }
x.report("capacity") { h = Hash.new(capacity: N); N.times { h[_1] = _1 } }
end
user system total real
default 0.156000 0.063000 0.219000 ( 0.209143)
capacity 0.188000 0.000000 0.188000 ( 0.181908)
Timings varied between runs, and in one of three runs the version with capacity was slower. Use it in hot code that builds big hashes of a known size, and measure.
Array#fetch_values (Ruby 3.4)
Hash#fetch_values (2.3) returns the values for several keys and raises KeyError if one is missing. Ruby 3.4 added the same method to Array. It's the strict version of values_at:
row = ["2026-10-18", "Ada", "ada@example.com", "admin"]
date, email = row.fetch_values(0, 2)
p [date, email]
p row.fetch_values(-1)
p row.values_at(1, 9) # nil for a missing index
p (row.fetch_values(1, 9) rescue $!) # error for a missing index
p row.fetch_values(1, 9) { |i| "<#{i} missing>" }
["2026-10-18", "ada@example.com"]
["admin"]
["Ada", nil]
#<IndexError: index 9 outside of array bounds: -4...4>
["Ada", "<9 missing>"]
Negative indexes count from the end, as with fetch. A block supplies a value for indexes that are out of bounds. For hashes the behaviour is the same, with KeyError:
config = {host: "localhost", port: 5432}
p config.fetch_values(:host, :port)
p (config.fetch_values(:host, :user) rescue $!)
["localhost", 5432]
#<KeyError: key not found: :user>
Prefer fetch_values over values_at when a missing value is a bug, for example when destructuring a CSV row that must have a fixed number of columns. You get an error at the point where the data is wrong instead of a nil that blows up somewhere else.
Array#rfind (Ruby 4.0)
find returns the first element for which the block is true. Array#rfind, new in Ruby 4.0, returns the last one:
events = [
{at: 1, type: :login, user: "ada"},
{at: 2, type: :view, user: "ada"},
{at: 3, type: :login, user: "grace"},
{at: 4, type: :logout, user: "ada"},
]
p events.find { _1[:type] == :login } # first match
p events.rfind { _1[:type] == :login } # last match
p events.rfind { _1[:type] == :crash }
p events.rfind(-> { :none }) { _1[:type] == :crash }
{at: 1, type: :login, user: "ada"}
{at: 3, type: :login, user: "grace"}
nil
:none
Like find, it returns nil when nothing matches, or calls the optional ifnone callable. It searches from the end, so it stops at the first match it sees from the back, and it doesn't create a reversed copy:
nums = (1..10).to_a
calls = 0
p nums.rfind { calls += 1; _1.even? }, calls
calls = 0
p nums.reverse_each.find { calls += 1; _1.even? }, calls
p nums.select(&:even?).last
p nums.rindex(&:even?)
p (1..10).respond_to?(:rfind), {a: 1}.respond_to?(:rfind)
10
1
10
1
10
9
false
false
reverse_each.find is the equivalent you can use on older Rubies; it's also lazy, just longer to write. select { }.last gives the same answer but checks every element and builds an intermediate array. rindex (which has accepted a block for a long time) gives you the index instead of the element. rfind exists only on Array: a general Enumerable can't be iterated backwards, so ranges and hashes don't have it.
Summary
| Method | Since | Replaces |
|---|---|---|
Hash#except(*keys) |
3.0 | reject with include? |
Hash#transform_keys(mapping) |
3.0 | transform_keys { mapping.fetch(_1, _1) } |
Array#intersect?(other) |
3.1 | (a & b).any? |
Enumerable#compact, Lazy#compact |
3.1 | reject(&:nil?) |
tally(hash) |
3.1 | merge of several tally results |
each_cons/each_slice return self |
3.1 | separate statements |
Lazy#eager |
3.1 | force / to_a |
Enumerator.product(*enums) |
3.2 | Array#product, nested loops |
Integer#ceildiv(n) |
3.2 | (a / n.to_f).ceil, -(-a / n) |
Hash.new(capacity: n) |
3.4 | {} |
Array#fetch_values(*idx) |
3.4 | values_at plus nil checks |
Array#rfind |
4.0 | reverse_each.find |
Ruby 3.1 also made the hash and keyword argument shorthand possible ({name:, email:}), which pairs well with except and slice; see Hash and keyword argument shorthand. For the range methods added in the same period (overlap?, reverse_each on beginless ranges, the new step), see Endless and beginless ranges.