2013-08-19 58 views
9

哈希時:未定義方法訪問哈希元件

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} 

嘗試調用p.pid但得到的錯誤:

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

所有其他元素可被訪問的罰款。也嘗試了不同的領域名稱,但無濟於事。任何人都可以對此有所瞭解嗎?真的希望它不是那些你長久以來只會意識到這是愚蠢的錯誤:/。

注:我也試過p ['pid']。這也沒有用。相對較新的Rails。

+2

使用'P [:PID]'的哈希值,與HashWithIndifferentAccess您可以使用符號:PID或字符串「 pid'來訪問值:'p ['pid']'或'p [:pid]'應該爲HashWithIndifferentAccess工作 – MrYoshiji

回答

19

嘗試是這樣的:

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

+0

謝謝你!很多! +1000 –

+3

那麼,這解決了問題,但爲什麼它是一個問題開始?我以爲'hash.key'和'hash [:key]'是同義詞嗎? – user1618143

+1

不幸的是,你不會從散列中獲得那些漂亮的方法。如果您需要使用方法訪問密鑰,則可以使用Ruby標準庫中的[OpenStruct](http://ruby-doc.org/stdlib-2.3.0/libdoc/ostruct/rdoc/OpenStruct.html)。 –