[英]Accessing elements of a ruby hash
Ruby 2.15
I defined the following hash: 我定义了以下哈希:
test = Hash.new
test["foo"] = {
'id' => 5,
'lobbyist_id' => 19,
'organization_id' => 8
}
If I do 如果我做
test.each do |t|
print t["id"]
end
I get: 我得到:
TypeError: no implicit conversion of String into Integer
from (irb):1571:in `[]'
How do I access the elements, using an each loop? 如何使用每个循环访问元素?
test.each do |t|
t.each do |t1|
puts t1["id"]
end
end
With a Hash, iteration is made through key first, then value. 对于哈希,首先通过键进行迭代,然后通过值进行迭代。 So have your block use what you need.
因此,让您的块使用所需的内容。
test.each do |key|
puts key
end
test.each do |key, value|
puts key
puts value
end
There are also 也有
test.each_key do |key|
puts key
end
test.each_value do |value|
puts value
end
Sidenote: id
is inside test["foo"]
, so maybe you'd need 2 loops 旁注:
id
在test["foo"]
,所以也许您需要2个循环
To get id
from your hash directly: 要直接从您的哈希获取
id
:
test["foo"]["id"]
test["foo"].each {|k, v| puts "#{k}: #{v}" }
In your example we assume you've previously done: 在您的示例中,我们假设您以前已经做过:
test = Hash.new
In your example variable test
is a hash and foo
is a key who's value contains a hash of key values. 在您的示例中,变量
test
是一个哈希,而foo
是一个键,其值包含键值的哈希。 If you want to target those, you'll need to loop over them 如果要定位这些目标,则需要遍历它们
test['foo'].each do |k,v|
puts "my key is #{k}"
puts "it's value is {v}
end
If you want to do both at the same time: 如果您要同时执行两个操作:
test.each do |k,v|
puts "base hash key #{k}"
puts "base hash value #{v}"
v.each do |kk,vv|
puts "key #{kk}"
puts "value #{vv}"
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.