【问题标题】:how do i get the uniq value for this hash?我如何获得此哈希的唯一值?
【发布时间】:2015-07-27 00:08:53
【问题描述】:

我想获取 uniq 区域并使用“状态 = 停止”进行过滤。 不使用任何循环。可能吗?

哈希:

{"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"}

我是红宝石和哈希的菜鸟。请帮忙^_^

【问题讨论】:

  • {"US-EAST", "US-WEST"} 不是有效的红宝石
  • 对不起 ["US-EAST", "US-WEST"] 我的意思是

标签: ruby ruby-on-rails-4 hash


【解决方案1】:
hash.map {|_,v| v['region'] if v['status'] == 'stopped'}.compact.uniq
# => ["US-EAST", "US-WEST"]

【讨论】:

    【解决方案2】:
     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"}]
    

    【讨论】:

    • 谢谢^_^。它现在正在工作。请再问 1 个问题,如果我想要键 ["region" => "US-EAST", "region" => "US-WEST"] 的结果怎么办
    • 很高兴为您提供帮助:)
    【解决方案3】:

    这是另一种方式:

    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"] 
    

    【讨论】:

    • 我已经考虑过这个(使用循环),但我想要的是一行代码 ^_^ 无论如何谢谢你的回答。
    猜你喜欢
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    • 2010-09-13
    • 2012-10-19
    相关资源
    最近更新 更多