假設我有兩個共享一個鍵(例如「foo」)但具有不同值的散列。現在我想創建一個具有一個屬性的方法,根據我選擇哪個散列作爲屬性來輸出密鑰的值。我怎麼做?輸出散列值的方法
我曾嘗試:
def put_hash(hash)
puts hash("foo")
end
,但是當我把這個功能用哈希它給了我下面的錯誤:
undefined method `hash' for main:Object (NoMethodError)
假設我有兩個共享一個鍵(例如「foo」)但具有不同值的散列。現在我想創建一個具有一個屬性的方法,根據我選擇哪個散列作爲屬性來輸出密鑰的值。我怎麼做?輸出散列值的方法
我曾嘗試:
def put_hash(hash)
puts hash("foo")
end
,但是當我把這個功能用哈希它給了我下面的錯誤:
undefined method `hash' for main:Object (NoMethodError)
您需要[]
訪問值:
puts hash["foo"]
否則Ruby認爲你正試圖調用一個方法()
,並且您看到一個錯誤,因爲在該範圍內沒有稱爲hash
的方法。
把它寫成
def put_hash(hash)
puts hash["foo"]
end
h1 = { "foo" => 1 }
h2 = { "foo" => 2 }
put_hash(h2) # => 2
看吧Hash#[]
元素參考,檢索對應於該鍵對象的值對象
你試過:
def put_hash(hash)
puts hash["foo"]
end
或者更好的是:
def put_hash(hash)
puts hash[:foo]
end
紅寶石存儲在這樣的哈希值:
{ :foo => "bar" }
或
{ "foo" => "bar" }
如果使用Symbol
或String
要訪問它們,您需要調用[]
方法Hash class
The Ruby Docs總是一個很好的起點。