Array (Ruby)
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]
- How to map/collect with index in Ruby?
arr.each_with_index.map { |x,i| [x, i+2] }
or
[:a, :b, :c].map.with_index(2).to_a
#=> [[:a, 2], [:b, 3], [:c, 4]]
see also
- Console table format in ruby
- ConsoleTable - a helper class that allows you to print data to a console in a clean, table-like fashion.
- String litterals
- How to Iterate the Right Way
- Shortest code
Written on October 9, 2021, Last update on March 28, 2025
ruby
array