Reputation: 86197
I've got a ruby data structure that looks like this:
my_item
=> {:data_id=>"some id",
:description=>
"some description",
:time=>"some time",
:name=>"some name"}
I assume it's a hash but if I try and access the data I get nil
back. e.g.:
puts my_item['name']
=> nil
How do you access the elements?
Upvotes: 1
Views: 106
Reputation: 4788
Strings and symbols aren't the same thing. If you use a symbol (:name
) as an index, you can't access it with a string:
foo = { :name => 'Hello' }
puts foo[:name] # => "Hello"
puts foo['name'] # => nil
Likewise, you can't use a symbol to access an element if a string ('name'
) is used:
bar = { 'name' => 'World' }
puts bar[:name] # => nil
puts bar['name'] # => "World"
Note that Ruby on Rails does allow strings and symbols to be interchanged to some degree - see the HashWithIndifferentAccess
documentation.
Upvotes: 2
Reputation: 122423
my_item
is a Hash, whose keys are all symbols (e.g, :name
), while you are using a string ('name'
) as the key.
my_item[:name]
# => "some name"
Upvotes: 1