Follow

I'm porting 2.7 Ruby to Ruby 3, and I'm having trouble iterating an array of hashes with de-structuring keyword args.

Previously, this worked:

a = [{:foo=>1, :bar=>1}, {:foo=>2, :bar=>2}]
a.each { |foo:, bar:| puts "foo: #{foo}, bar: #{bar}" }

With , how do you de-structure each item inline? 🤔

So, the solution is to not use this Ruby 2 feature anymore. I've taken to using pattern-matching instead.

Yes, it is more verbose in some cases. Not a big deal.

@oz I didn't even realize a block could take kwargs. I've only seen them used in method definitions. That's pretty cool!

The best I could come up with was explicit destructuring:

a.each { ->(foo:, bar:) { puts "foo: #{foo}, bar: #{bar}" }.call **_1 }

Or pattern matching like you said:

a.each { _1 => {foo:, bar:}; puts "foo: #{foo}, bar: #{bar}" }

Sign in to participate in the conversation
Ruby.social

A Mastodon instance for Rubyists & friends