1 min read

TIL: Array Denaturing in Ruby

Ruby arrays can be automatically denatured

Ruby arrays can be automatically denatured.

Consider this:

array = [[1,2], [3,4], [5,6]]
array.each { |x| p x }
[1, 2]
[3, 4]
[5, 6]

Ruby let's you automatically denature the sub-array:

array = [[1,2], [3,4], [5,6]]
array.each { |x, y| p x + y }
3
7
11

It makes no difference but I like using parenthesis which feels a bit more explicit to my mind:

array.each { |(x, y)| p x + y }