I Ruby 2 you could do the following:
my_hash = {a: {aa: 1, ab: 2, ac: 3}}
my_hash.each do |key, aa:, ab: 4, **|
puts key
puts aa
puts ab
end
In Ruby 3 this now results in missing keywords :aa, :ab. What would be the best way to refactor code like this in Ruby 3?
Something like the following would not work because it doesn't support setting default values:
my_hash.each do |key, values|
values in {aa: aa, ab: ab}
end
The best way I can think of is putting the existing code in a wrapper:
lambda = ->(key, aa:, ab: 4, **) do
puts key
puts aa
puts ab
end
my_hash.each do |key, values|
lambda.call(key, **values)
end
Any better options?
I can't think of a way to convert the hash to keyword arguments.
But why not use the hash the way it is, i.e. without treating its keys like keywords? Unless your actual code is more complex,
fetchseems to do what you want:The above works fine in both, Ruby 2 and 3. Just like your example, it will raise an error if
:aais missing and it will use a default value of4if:abis missing.