Reputation: 15
I am trying to get data from PostgreSQL with ruby and store them into an array, for that I have a small script:
Script :
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(",")
The outcome is :
{"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 "}
What I need is just the name of each domain name! Something like {"youtube.com","google.com","java.com","rails.com","hp.com"}
Any suggestions would be greatly appreciated.
Upvotes: 1
Views: 66
Reputation: 3356
Taking your code only, and doing small changes, I guess following will work for you
a_dns = []
res.each { |r| a_dns << r.values[0].strip }
puts a_dns
Upvotes: 0
Reputation: 118299
I think you need :
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 }
Upvotes: 3