[英]How do I loop over a hash of hashes?
I have this hash:我有这个哈希:
h
=> {"67676.mpa"=>{:link=>"pool/sdafdsaff", :size=>4556}}
> h.each do |key, value|
> puts key
> puts value
> end
67676.mpa
linkpool/sdafdsaffsize4556
How do I access the separate values in the value hash on the loop?如何访问循环中值哈希中的单独值?
Value is a Hash to so you need iterate on it or you can get only values:-值是一个哈希值,因此您需要对其进行迭代,否则您只能获得值:-
h.each do |key, value|
puts key
value.each do |k,v|
puts k
puts v
end
end
or要么
h.each do |key, value|
puts key
value.values.each do |v|
puts v
end
end
You'll want to recurse through the hash, here's a recursive method:您需要通过哈希递归,这是一个递归方法:
def ihash(h)
h.each_pair do |k,v|
if v.is_a?(Hash)
puts "key: #{k} recursing..."
ihash(v)
else
# MODIFY HERE! Look for what you want to find in the hash here
puts "key: #{k} value: #{v}"
end
end
end
You can Then take any hash and pass it in:然后,您可以获取任何散列并将其传入:
h = {
"x" => "a",
"y" => {
"y1" => {
"y2" => "final"
},
"yy1" => "hello"
}
}
ihash(h)
I little improved Travis's answer, how about this gist:我几乎没有改进 Travis 的回答,这个要点怎么样:
https://gist.github.com/kjakub/be17d9439359d14e6f86 https://gist.github.com/kjakub/be17d9439359d14e6f86
class Hash
def nested_each_pair
self.each_pair do |k,v|
if v.is_a?(Hash)
v.nested_each_pair {|k,v| yield k,v}
else
yield(k,v)
end
end
end
end
{"root"=>{:a=>"tom", :b=>{:c => 1, :x => 2}}}.nested_each_pair{|k,v|
puts k
puts v
}
The simplest way to separate out all three values in this case would be as follows:在这种情况下,分离所有三个值的最简单方法如下:
h.each do |key, value|
puts key
puts value[:link]
puts value[:size]
end
You can access the values of a hash directly by calling hash.values
.您可以通过调用hash.values
直接访问哈希值。 In this case you could do something like在这种情况下,你可以做类似的事情
> h = {"67676.mpa"=>{:link=>"pool/sdafdsaff", :size=>4556}}
> h.values.each do |key, value|
> puts "#{key} #{value}"
> end
link pool/sdafsaff
size 4556
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.