2013-06-28 29 views
-2

假设我有两个共享一个键(例如“foo”)但具有不同值的散列。现在我想创建一个具有一个属性的方法,根据我选择哪个散列作为属性来输出密钥的值。我怎么做?输出散列值的方法

我曾尝试:

def put_hash(hash) 
    puts hash("foo") 
end 

,但是当我把这个功能用哈希它给了我下面的错误:

undefined method `hash' for main:Object (NoMethodError) 

回答

1

您需要[]访问值:

puts hash["foo"] 

否则Ruby认为你正试图调用一个方法() ,并且您看到一个错误,因为在该范围内没有称为hash的方法。

0

把它写成

def put_hash(hash) 
    puts hash["foo"] 
end 
h1 = { "foo" => 1 } 
h2 = { "foo" => 2 } 
put_hash(h2) # => 2 

看吧Hash#[]

元素参考,检索对应于该键对象的值对象

1

你试过:

def put_hash(hash) 
    puts hash["foo"] 
end 

或者更好的是:

def put_hash(hash) 
    puts hash[:foo] 
end 

红宝石存储在这样的哈希值:

{ :foo => "bar" } 

{ "foo" => "bar" } 

如果使用SymbolString

根据

要访问它们,您需要调用[]方法Hash class

The Ruby Docs总是一个很好的起点。