I have a hash which looks like this:
items:
item:
attribute_a: cheese
attribute_b: bacon
item:
attribute_a: salmon
item:
attribute_a: mushrooms
attribute_b: steak
I would like to get the value of attribute_b, I’m using the following:
if (result['attribute_b'])
// do something
end
However if attribute_b is missing, I get an error:
The Identifier specified does not exist, undefined method '[] for nil:NilClass'
What is the (best) correct way to check if attribute_b exists?
It looks as if you’re getting the error not upon accessing the attribute
'attribute_b', but becauseresultis nil.It’s saying you’re calling the method
[]on a nil value. The only thing you’re calling ‘[]‘ on isresult.The way you’re accessing
'attribute_b'is acceptable in general — I might be more specific and say:This will make sure that
resultexists as well as making sure the attribute is not null.