Redline Software Inc. - Winnipeg's Leader in Ruby on Rails Development

Ruby Syntax Tip

I’ve had quite a few moments while using Ruby when I decide to try to write something that I think should be valid Ruby without knowing if it actually is and it ends up working.

Here’s one of my latest finds using for loops…

1
2
3
  for a, b, c in [[1,2,3], [4,5,6], [7,8,9]]
    puts "#{a}, #{b}, #{c}"
  end

Results in…

1
2
3
  1, 2, 3
  4, 5, 6
  7, 8, 9

The for loop lets you can assign multiple values at the same time which is exactly what you can do with arrays with basic assignment elsewhere in Ruby code.

1
  a, b, c = [1, 2, 3]

I knew I could assign multiple values from an array like this, but had never tried it in a for loop before. Ruby ftw!

Comments