Destructure a Hash in block arguments in Ruby 2.7

Viewed 1690

This:

[{a: 1, b: 2}, {a: 3, b: 4}].each do |a:, b:| p a end

Raises the following warning in Ruby 2.7

warning: Using the last argument as keyword parameters is deprecated; maybe ** should be added to the call

I understand that each is passing a hash to the block, and the block now accepts |a:, b:| as named arguments but, is there any way to correctly destructure the hash in this context?

2 Answers

I'm uncertain, but I think perhaps the idea is to use pattern matching for hash destructuring? For example:

{a: 1, b: 2}.tap do |args|
  args in {a: a, b: b} # !!!
  p a
end

Currently by default however, this will display a warning (which can be disabled):

Pattern matching is experimental, and the behavior may change in future versions of Ruby!

If you already know that you have two keys in each Hash as per your example, why not this?

[{a: 1, b: 2}, {a: 3, b: 4}].each do |h|
  a, b = h.values
  p a
end
Related