user1134991 user1134991 - 6 months ago 8
Ruby Question

How can one loop in a ruby with 2 variables on Array

In Tcl, if you have a list with even elements, one can loop two elements at a time. See this code:

foreach { a b } [ list 1 2 3 4 ] {
puts "${a} ${b}"
}


Will output:


1 2
3 4


How can one get the same behavior with Ruby?

Answer

You can get same output by this way:

[1,2,3,4].each_slice(2) {|a, b| puts "#{a} #{b}" }