leejay100
leejay100

Reputation: 221

Group Elements by Each in Array

In Ruby, how would I group elements in an array until I find a different element? For example:

array = [1, 1, 2, 3, 3, 1, 5, 6, 2]

I'd like to iterate through it, but up until the next element is different. I don't want to sort it because it still needs to be in that order. So if I were going through this array:

for [1, 1] do X  
for [2] do Y  
for [3, 3] do Z  
for [1] do X

Upvotes: 0

Views: 503

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118261

Here is another way :

array = [1, 1, 2, 3, 3, 1, 5, 6, 2]
array.group_by(&:itself).values
# => [[1, 1, 1], [2, 2], [3, 3], [5], [6]]

Look #itself method.

If you have not asked above, then #slice_when is your way to go :

array.slice_when { |i,j|  i != j }.to_a
# => [[1, 1], [2], [3, 3], [1], [5], [6], [2]]
array.slice_when { |i,j|  i != j }.each { |n| p "do_something_with_#{n}" }
# "do_something_with_[1, 1]"
# "do_something_with_[2]"
# "do_something_with_[3, 3]"
# "do_something_with_[1]"
# "do_something_with_[5]"
# "do_something_with_[6]"
# "do_something_with_[2]"

Upvotes: 4

Related Questions