我想获取uniq区域并使用“status = stopped”进行过滤。 不使用任何循环。可能吗?
散列:
{"a123" => {"status"=>"stopped", "region"=>"US-EAST"},
"b123" => {"status"=>"stopped", "region"=>"US-EAST"},
"c123" => {"status"=>"stopped", "region"=>"US-WEST"},
"d123" => {"status"=>"running", "region"=>"US-WEST"},
"e123" => {"status"=>"running", "region"=>"US-NORTH"}}
我的过滤状态代码:
hash.select{ |k, v| v["status"] == "stopped" }.values
#=> [{"status"=>"stopped", "region"=>"US-EAST"},
{"status"=>"stopped", "region"=>"US-EAST"},
{"status"=>"stopped", "region"=>"US-WEST"}]
我不知道接下来要做什么,我希望输出为:
#=> {"US-EAST", "US-WEST"}
我是红宝石和哈希的菜鸟。请帮忙^ _ ^
答案 0 :(得分:3)
hash.map {|_,v| v['region'] if v['status'] == 'stopped'}.compact.uniq
# => ["US-EAST", "US-WEST"]
答案 1 :(得分:1)
hash.select{ |k,v| v["status"] == "stopped" }.values.map { |e| e["region"] }.uniq
=> ["US-EAST", "US-WEST"]
# use `map` method to put region to an array
hash.select{ |k,v| v["status"] == "stopped" }.values.map { |e| e["region"] }
=> ["US-EAST", "US-EAST", "US-WEST"]
#then use the `uniq` method remove repeated.
["US-EAST", "US-EAST", "US-WEST"].uniq
=> ["US-EAST", "US-WEST"]
hash.select{ |k,v| v["status"] == "stopped" }.values.map{ |e| {"region" => e["region"]}}.uniq
=> [{"region"=>"US-EAST"}, {"region"=>"US-WEST"}]
答案 2 :(得分:1)
这是另一种方式:
require 'set'
hash.each_with_object(Set.new) do |(_,h),s|
s << h["region"] if h["status"]=="stopped"
end.to_a
#=> ["US-EAST", "US-WEST"]