Home > Net >  Getting data from result set and transposing to file Ruby
Getting data from result set and transposing to file Ruby

Time:01-28

I have result set with some information about a client like

[{name: John, age:20, state:y, city:w, country:x,...},{name:.....}]

Now I want to loop through this list getting only name, state, and city. And create a file with this information in the following format

name | age | city

How can I do this? I thought about adding to a 3d list and then transposing to csv. But I don't like this idea.

CodePudding user response:

CSV is not that hard to do (using the test data from @dawg):

require 'csv'
a [{name: "John", age:20, state:"ID", city:"Boise", country:"USA"},
  {name: "Bob", age:20, state:"CA", city:"LA", country:"USA"}
]

File.open("test.csv","w") do |f|
  a.each{|hsh| f <<  hsh.values_at(:name, :age, :city).to_csv}
end

CodePudding user response:

Given:

a=[{name: "John", age:20, state:"ID", city:"Boise", country:"USA"},
   {name: "Bob", age:20, state:"CA", city:"LA", country:"USA"}
]

headers=[:name, :age, :city]

You can do:

> a.map{|hsh| hsh.slice(*headers) }
=> 
[{:name=>"John", :age=>20, :city=>"Boise"},
 {:name=>"Bob", :age=>20, :city=>"LA"}]

And if you want that format:

puts headers.join(" | ")
a.map{|hsh| hsh.slice(*headers) }.
    each{|hsh| puts hsh.values.join(" | ")}

Prints:

name | age | city
John | 20 | Boise
Bob | 20 | LA
  • Related