我正在尝试使用ruby从PostgreSQL获取数据并将它们存储到一个数组中,因为我有一个小脚本:
脚本:
require 'pg'
conn=PGconn.connect( :hostaddr=>"192.168.111.136", :port=>5432, :dbname=>"sentinel_poc",:user=>"sdn_mehdi", :password=>'skyline123')
res = conn.exec("SELECT dns_name FROM dns_table group by dns_name").to_a
a_dns = []
res.each { |r| a_dns << r }
puts a_dns.join(",")
结果是:
{"dns_name"=>"youtube.com "},{"dns_name"=>"stackoverflow.com "},{"dns_name"=>"cisco.com "},{"dns_name"=>"facebook.com "},{"dns_name"=>"yahoo.com "},{"dns_name"=>"onf.com "},{"dns_name"=>"safe.com "},{"dns_name"=>"linkedin.com "},{"dns_name"=>"amazon.com "},{"dns_name"=>"google.com "},{"dns_name"=>"java.com "},{"dns_name"=>"live.com "},{"dns_name"=>"rails.com "},{"dns_name"=>"postgresql.com "},{"dns_name"=>"hp.com "},{"dns_name"=>"wikipedia.org "}
我需要的只是每个域名的名称!像{"youtube.com","google.com","java.com","rails.com","hp.com"}
任何建议都将不胜感激。
答案 0 :(得分:3)
我认为你需要:
res.flat_map(&:values)
# or if you have hashes having size more then 1, then use the below
res.map { |h| h["dns_name"] }
# to strip leading and trailing whit spaces
res.map { |h| h["dns_name"].strip }
答案 1 :(得分:0)
仅使用您的代码并进行小的更改,我想以下内容对您有用
a_dns = []
res.each { |r| a_dns << r.values[0].strip }
puts a_dns