but I think that’s not very beautiful - think about a case where I have
to check whether param[:a][:b][:c][:d][:…] exists or not!
Maybe there’s a cooler way to do this?
Yes: design your data structures with classes and modules and methods,
instead of quintuply-nested hashes But if you want to have a hash
that automatically inserts a hash for an unknown key, you can do:
irb(main):001:0> a = {:a=>{:x=>1}}
=> {:a=>{:x=>1}}
irb(main):003:0> p a[:a][:x]
1
=> nil
irb(main):004:0> p a[:a][:y]
nil
=> nil
irb(main):005:0> p a[:b][:x]
NoMethodError: undefined method `[]’ for nil:NilClass
from (irb):5
when param[:x] is nil. So I always have to use
Thanks
Josh
You can use the rescue modifier, like this:
if (param[:x][:y] rescue nil)
…
end
The expression in brackets will return the value of param[:x][:y] but if
param[:x][:y] raises an exception derived from StandardError (like
NoMethodError), the exception will be caught by the rescue modifier, and
the
statement to the right of rescue (nil) will be returned.
That only works if param[:x] exists. It’s also not perfect, since
[aram[:x][:y] can return a non-nil value if param[:x] exists but is
not an array… so you probably need to check for that case also.
To my knowledge, the only way you could handle this easily would be to
rescue the NoMethodError as follows:
param[:x][:y] rescue NoMethodError { nil } # return nil if
NoMethodError is raised
Although that’s tricky too, as depending on the nature of your object
structure, you may catch a NoMethodError you didn’t intend to catch.