user1134991 user1134991 - 1 year ago 47
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 Source

You can get same output by this way:

[1,2,3,4].each_slice(2) {|a, b| puts "#{a} #{b}" }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download