Array (Ruby)

ruby-doc

it (Ruby 3.4)

ary = ["foo", "bar", "baz"]

p ary.map { it.upcase } #=> ["FOO", "BAR", "BAZ"]

it very much behaves the same as _1. When the intention is to only use _1 in a block, the potential for other numbered parameters such as _2 to also appear imposes an extra cognitive load onto readers. So it was introduced as a handy alias. Use it in simple cases where it speaks for itself, such as in one-line blocks.

First and Rest in Ruby

many = [0,1,2,3,4]
first, rest = many.first, many[1..-1]

splat operator

turn an Array into an argument list

arguments = [2, 3]
my_method(1, *arguments)
# equivalent to 
my_method(1, 2, 3)

the inverse is to gather arguments as if they were in an array

def my_method(*a, **kw)
  p arguments: a, keywords: kw
end

Splitting an array into equal parts in ruby

a = [0, 1, 2, 3, 4, 5, 6, 7]
a.each_slice(3) # => #<Enumerator: [0, 1, 2, 3, 4, 5, 6, 7]:each_slice(3)>
a.each_slice(3).to_a # => [[0, 1, 2], [3, 4, 5], [6, 7]

see also

Written on October 9, 2021, Last update on March 28, 2025
ruby array