In Ruby 3,
hash => {a:}
works similarly to JS
{ a } = hash
except it throws an exception if :a isn't a key in hash instead of assigning a = nil. Ok, we can do
hash => {a:} rescue nil
except this gives undesired result if some keys are present and others missing:
{a: 1, b: 2} => {b:, c:} rescue nil
puts "b: #{b}, c: #{c}"
shows b and c are both nil instead of the desired b = 2, c = nil. Is there a simple way to get that result? Or even more generally, emulate JS hash destructuring with non-nil default values?
You can work around missing key error by making an object that responds to
deconstruct_keys:deconstruct_keysis called when hash pattern is used=> x:,y:,a:, these keys are passed as argument:https://docs.ruby-lang.org/en/3.2/syntax/pattern_matching_rdoc.html#label-Matching+non-primitive+objects-3A+deconstruct+and+deconstruct_keys