Array (Ruby)
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 June 13, 2024
ruby
array