Tom
Tom

Reputation: 34366

Hash missing value, throwing exception

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?

Upvotes: 0

Views: 1679

Answers (2)

Kevin Bedell
Kevin Bedell

Reputation: 13404

It looks as if you're getting the error not upon accessing the attribute 'attribute_b', but because result is nil.

The Identifier specified does not exist, undefined method [] for nil:NilClass`

It's saying you're calling the method [] on a nil value. The only thing you're calling '[]' on is result.

The way you're accessing 'attribute_b' is acceptable in general -- I might be more specific and say:

if (result && result.has_key? 'attribute_b')
 // do something
end

This will make sure that result exists as well as making sure the attribute is not null.

Upvotes: 2

Patrick Oscity
Patrick Oscity

Reputation: 54684

First of all, your YAML structure looks bad (is it YAML?). You cannot have a hash with more than one element with the key item, because the key must be unique. You should use an array instead.

I suggest you structure you YAML along the lines of this here:

items:
  -
    attribute_a: cheese
    attribute_b: bacon
  -
    attribute_a: salmon
  -
    attribute_a: mushrooms
    attribute_b: steak

Then you can do

require 'yaml'
result = YAML.load(File.open 'foo.yml')
result['items'][0]['attribute_b']
=> "bacon"

Upvotes: 0

Related Questions