Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe navigation operator (lonely operator) not working for hash

Tags:

ruby

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?

like image 919
eiko Avatar asked Oct 24 '25 04:10

eiko


1 Answers

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.

like image 130
Ursus Avatar answered Oct 25 '25 19:10

Ursus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!