Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting ruby array to array of consecutive pairs

Tags:

arrays

ruby

What is the easiest way to convert a ruby array to an array of consecutive pairs of its elements?

I mean:

x = [:a, :b, :c, :d]

Expected result:

y #=> [[:a, :b], [:c, :d]]
like image 626
Ivan Kataitsev Avatar asked Aug 13 '10 14:08

Ivan Kataitsev


People also ask

What does .last do in Ruby?

Ruby | Array class last() function last() is a Array class method which returns the last element of the array or the last 'n' elements from the array. The first form returns nil, If the array is empty .

How do you convert an array of strings to integers in Ruby?

Converting Strings to Numbers Ruby provides the to_i and to_f methods to convert strings to numbers. to_i converts a string to an integer, and to_f converts a string to a float.

How do you concatenate an array in Ruby?

This can be done in a few ways in Ruby. The first is the plus operator. This will append one array to the end of another, creating a third array with the elements of both. Alternatively, use the concat method (the + operator and concat method are functionally equivalent).

Can you split an array Ruby?

split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified. Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.


2 Answers

Use Enumerable#each_slice:

y = x.each_slice(2).to_a #=> [[:a, :b], [:c, :d]]  [0, 1, 2, 3, 4, 5].each_slice(2).to_a #=> [[0, 1], [2, 3], [4, 5]] 
like image 100
deinst Avatar answered Sep 25 '22 02:09

deinst


Hash[*[:a, :b, :c, :d]].to_a
like image 30
Daniel O'Hara Avatar answered Sep 25 '22 02:09

Daniel O'Hara