Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby array access 2 consecutive(chained) elements at a time

Tags:

arrays

each

ruby

Now, This is the array,

[1,2,3,4,5,6,7,8,9] 

I want,

[1,2],[2,3],[3,4] upto [8,9] 

When I do, each_slice(2) I get,

[[1,2],[3,4]..[8,9]] 

Im currently doing this,

arr.each_with_index do |i,j|   p [i,arr[j+1]].compact #During your arr.size is a odd number, remove nil. end 

Is there a better way??

like image 343
beck03076 Avatar asked Mar 28 '13 12:03

beck03076


People also ask

What does the .each method do in Ruby?

The "each" method in Ruby on Rails allows you to iterate over different objects inside an array-like structure.

What does .first mean in Ruby?

Ruby | Array class first() function first() is a Array class method which returns the first element of the array or the first 'n' elements from the array.

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

Ruby reads your mind. You want cons ecutive elements?

[1, 2, 3, 4, 5, 6, 7, 8, 9].each_cons(2).to_a # => [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9]] 
like image 93
Jörg W Mittag Avatar answered Oct 26 '22 03:10

Jörg W Mittag


.each_cons does exactly what you want.

[1] pry(main)> a = [1,2,3,4,5,6,7,8,9] => [1, 2, 3, 4, 5, 6, 7, 8, 9] [2] pry(main)> a.each_cons(2).to_a => [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9]] 
like image 37
Dogbert Avatar answered Oct 26 '22 04:10

Dogbert