Search code examples
rubyhashruby-on-rails-5

Trying to check for content in my Hash but getting "undefined method `&' for Hash" error


I'm writing a Ruby on rails (5) application. I was trying to simplify this block

if my_hash_data[:my_key_1]
  my_hash_data[:my_key_1][:my_key_2]
else
  ""
end

and so I wrote

my_hash_data[:my_key_1]&[:my_key_2] || ""

However this results in an

undefined method `&' for {:my_key_2=>"Y"}:Hash

error. Is there another way I can write this to cut down on the lines I'm using?


Solution

  • Yes, this is what you're trying to do

    my_hash_data[:my_key_1]&.[](:my_key_2) || ""
    

    but I suggest using dig from ruby 2.3 onward

    my_hash_data.dig(:my_key_1, :my_key_2) || ""
    

    Remember that h[:foo] is syntactic sugar for h.[](:foo)