I'm trying to use the safe navigation operator & to optionally call the [] method on a variable which may be a hash or nil. As far as I know, that's what safe navigation operators are for.
my_hash = nil
puts "hello, #{ my_hash&[:test] }"
my_hash = { test: "world" }
puts "hello, #{ my_hash&[:test] }"
I expect this to output:
hello, false
hello, world
But but it does not work with hashes; instead, I get:
hello, false
undefined method `&` for `{:test=>"world"}:Hash` (NoMethodError)
What am I doing wrong?
Because this
my_hash[:test]
is syntactic sugar for this one
my_hash.[](:test)
so this should work
my_hash&.[](:test)
but it's not pretty, I know.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With