Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if hash is nil before checking specific attribute

What I'm currently doing is

"Hello" if options && options[:greet]

What I would like to do is cut that line down. If options is nil, options[:greet] obviously will be too. Does Ruby/Rails provide a method that offers this "hash checking" ability? Or perhaps there's a way of writing this more succinctly?

like image 829
Dan Avatar asked Oct 18 '25 08:10

Dan


1 Answers

There's also one more shortcut, I tend to use it more often, when I don't have control over options variable (i.e. it may be either nil or hash):

options.to_h[:greet] # just convert it to a hash before key access

Note, that it works only starting from Ruby 2.0.

like image 93
Alexey Shein Avatar answered Oct 19 '25 23:10

Alexey Shein



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!