我有这样的哈希:
members = { "name1" => { "country" => "country1", "city" => "city1"}, "name2" => { "country" => "country2", "city" => "city2"} }
如何通过此哈希获取一系列国家/地区:
countries = [ "country1", "country2" ]
答案 0 :(得分:2)
require 'benchmark'
Benchmark.bm do |x|
x.report { members.map { |_,v| v["country"] } }
x.report { members.collect { |_,v| v["country"] } }
x.report { members.values.map{|h| h["country"]} }
end
user system total real
0.000000 0.000000 0.000000 ( 0.000014)
0.000000 0.000000 0.000000 ( 0.000011)
0.000000 0.000000 0.000000 ( 0.000020)
=> ["country1", "country2"]
因此,请使用members.collect { |_,v| v["country"] }
,因为它是最快的。
答案 1 :(得分:0)
countries = members.to_a.map(&:last).map{|h| h["country"]}
我测试了它应该可以工作。