Nacho321
Nacho321

Reputation: 1991

Iterate through list two by two in ruby

I have a list that looks like:

list = 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'

I want to iterate through it two by two, so that I can modify 'a' and 'b' in the same iteration. This would be the java equivalent of what I need to do:

for (int i = 0; i < list.size(); i+=2){
    System.out.println(list.get(i) + list.get(i+1));
}

Upvotes: 1

Views: 274

Answers (3)

Wand Maker
Wand Maker

Reputation: 18762

Here are few more ways:

  1. Using Range#step

    (0...list.size).step(2).map { |i| list.values_at(i, i.next).join }
    #=> ["ab", "cd", "ef", "gh"]
    
  2. By grouping the values by their position in array

    list.group_by.with_index {|_, idx| idx.even?}.values.transpose.map(&:join)
    #=> ["ab", "cd", "ef", "gh"]
    

Upvotes: 2

Ilya
Ilya

Reputation: 13477

You can use each_slice for it:

list.each_slice(2) { |first, second| p first + second }
=> "ab"
"cd"
"ef"
"gh"

When you use each_slice(2), you pass in block array like ["a", "b"] on each iteration. Size of array depends on each_slice argument. Then, in block, happens next:

first, second = ["a", "b"]
first 
#=>"a"
second
#=>"b"

Upvotes: 7

Simone Carletti
Simone Carletti

Reputation: 176372

You can use the Enumerable#each_slice

list.each_slice(2) { |x,y| p "#{x} #{y}" }

Upvotes: 6

Related Questions