Destructuring assignment in block parameters

…which is just a fancy way to say that this works like I think it should:

>> [['foo', 1], ['bar', 2], ['honk', 1000]].partition { |str, val| val > 999 }
=> [[["honk", 1000]], [["foo", 1], ["bar", 2]]]

Which beats the pants off this:

>> [['foo', 1], ['bar', 2], ['honk', 1000]].partition do |pair|
?>     str, val = pair
>>     val > 999
>>   end
=> [[["honk", 1000]], [["foo", 1], ["bar", 2]]]

So, you see, the array elements get unpacked into @str@ and @val@ inside your block. Which is unexpected, but totally and thoroughly lovely. To my eyes, the former is much easier to read.

2 thoughts on “Destructuring assignment in block parameters

  1. And if you have no use for one of the arguments passed to the block I tend to name the unused argument _.

    For example:

    name_to_age_mapping.partition do |_, age|
    age > minimum_age

Comments are closed.