Reputation: 1991
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
Reputation: 18762
Here are few more ways:
Using Range#step
(0...list.size).step(2).map { |i| list.values_at(i, i.next).join }
#=> ["ab", "cd", "ef", "gh"]
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
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
Reputation: 176372
You can use the Enumerable#each_slice
list.each_slice(2) { |x,y| p "#{x} #{y}" }
Upvotes: 6