Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 603
user1134991 Avatar asked Apr 22 '26 07:04

user1134991


2 Answers

You can get the same output by this way:

[1,2,3,4].each_slice(2) {|a, b| puts "#{a} #{b}" }
like image 85
Ilya Avatar answered Apr 24 '26 00:04

Ilya


puts [1,2,33,44].join(' ').scan /\d+\s\d+/
1 2
33 44
like image 31
Cary Swoveland Avatar answered Apr 24 '26 00:04

Cary Swoveland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!