16

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.

Kirsty Williams
  • 340
  • 1
  • 2
  • 10
  • 2
    Use `p[:pid]` for Hashes, with HashWithIndifferentAccess you can either use the symbol :pid or the string 'pid' to acces the value: `p['pid']` or `p[:pid]` should work for HashWithIndifferentAccess – MrYoshiji Aug 19 '13 at 14:34

1 Answers1

30

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

ajt
  • 553
  • 8
  • 25
  • 6
    Well, that fixes the problem, but why was it a problem to begin with? I thought `hash.key` and `hash[:key]` were synonymous? – user1618143 Dec 12 '14 at 16:20
  • 3
    You don't get those nice methods from a hash, unfortunately. If you need to access keys with a method, you can use an [OpenStruct](http://ruby-doc.org/stdlib-2.3.0/libdoc/ostruct/rdoc/OpenStruct.html) from the Ruby standard library. – Joshua Plicque Jan 21 '16 at 18:12