Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined method when accessing hash element

Hash:

p: {:headline=>"Managing Director at Test company name", :pid=>"0tSsRvCR7r", :first_name=>"John", :last_name=>"Doe", :industry=>"Financial Services", :summary=>nil, :public_profile_url=>"http://www.linkedin.com/pub/john-doe/7a/78/606", :distance=>0}

Attempting to call p.pid but getting the error:

EXCEPTION: undefined method `pid' for #<Hash:0x007fcf1b3a29f0> 

All other elements can be accessed fine. Also tried different names for the field but to no avail. Can anyone shed some light on this please? Really hoping it's not one of those bugs that you stare at for ages only to realise it's something silly :/.

Note: I have also tried p['pid']. This didn't work either. Relatively new to Rails.

like image 459
Kirsty Williams Avatar asked Aug 19 '13 14:08

Kirsty Williams


People also ask

What is hash in Ruby?

In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order.

What is key and value in hash?

The key is sent to a hash function that performs arithmetic operations on it. The result (commonly called the hash value or hash) is the index of the key-value pair in the hash table.

Are Ruby hashes ordered?

Hashes are inherently unordered. Hashes provide amortized O(1) insertion and retrieval of elements by key, and that's it. If you need an ordered set of pairs, use an array of arrays.

What is a hash pair?

Entries in a hash are often referred to as key-value pairs. This creates an associative representation of data. Most commonly, a hash is created using symbols as keys and any data types as values. All key-value pairs in a hash are surrounded by curly braces {} and comma separated.


1 Answers

Try something like this :

p = {:headline=>"Managing Director at Test company name", :pid=>"0tSsRvCR7r", :first_name=>"John",     :last_name=>"Doe", :industry=>"Financial Services", :summary=>nil,     :public_profile_url=>"http://www.linkedin.com/pub/john-doe/7a/78/606", :distance=>0}
puts p
puts p[:pid]

hash docs

more on hashes

like image 142
ajt Avatar answered Sep 22 '22 15:09

ajt