Array (Ruby)

ruby-doc

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 June 13, 2024
ruby array