Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructure a Hash in block arguments in Ruby 2.7

Tags:

ruby

ruby-2.7

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?

like image 256
Daniel Avatar asked Jun 04 '20 07:06

Daniel


1 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!

like image 59
Tom Lord Avatar answered Oct 16 '22 08:10

Tom Lord