我需要一个循环来迭代看起来类似于下面的哈希:
{:client=>"CLIENT1", :mwregion=>"prod", :db=>"DBAB2", :host=>"10.193.138.23", :role=>"WEB"}
{:client=>"CLIENT1 ", :mwregion=>"prod", :db=>"DBAB2", :host=>"10.192.138.24", :role=>"WEB"}
{:client=>"CLIENT1 ", :mwregion=>"prod", :db=>"DBAB2", :host=>"10.193.138.24", :role=>"WEB"}
{:client=>"CLIENT1 ", :mwregion=>"beta", :db=>"DBAB5", :host=>"10.192.140.61", :role=>"WEB"}
{:client=>"CLIENT2 ", :mwregion=>"beta", :db=>"DBAB2", :host=>"10.193.140.61", :role=>"WEB"}
{:client=>"CLIENT2 ", :mwregion=>"train", :db=>"DBAB2", :host=>"10.192.140.59", :role=>"WEB"}
{:client=>"CLIENT2 ", :mwregion=>"train", :db=>"DBAB4", :host=>"10.193.140.59", :role=>"WEB"}
{:client=>"CLIENT3 ", :mwregion=>"prod", :db=>"DBAB3", :host=>"10.192.139.61", :role=>"JVM"}
{:client=>"CLIENT3 ", :mwregion=>"prod", :db=>"DBAB1", :host=>"10.193.139.63", :role=>"JVM"}
并打印出:client key的唯一值。
CLIENT1
CLIENT2
CLIENT3
我尝试了以下内容,但失败了
@var.uniq do |x|
puts x[:client]
end
main.rb:12:in `<main>': undefined method `uniq' for #<Sequel::MySQL::Dataset:0x000000011ca1a0> (NoMethodError)
此外,ruby版本是:
ruby -v
ruby 1.9.3p545 (2014-02-24 revision 45159) [x86_64-linux]
答案 0 :(得分:1)
很难说明您提供的信息 - 很明显,您不会像问题所说的那样迭代哈希,而是其他东西(MySQL :: Dataset) )?
如果背后有数据库,最简单的方法是首先更改生成这些记录的查询,可能在查询中使用GROUP BY client
子句。
相反,如果你实际上有一个哈希数组,那么试试这个:
>> @var.map {|h| h[:client]}.uniq
=> ["CLIENT1", "CLIENT1 ", "CLIENT2 ", "CLIENT3 "]
或者,因为你有尾随空格,可能是:
>> @var.map {|h| h[:client].strip}.uniq
=> ["CLIENT1", "CLIENT2", "CLIENT3"]
答案 1 :(得分:0)
你所拥有的显然既不是数组也不是哈希,而是Sequel :: Dataset。所以我认为你想要的是@var.distinct(:client)
。