Ruby - Output file in CSV comes in one column
I think this should work:
CSV.open(fn, "wb") do |csv|
data.each do |name, values|
csv << [name, *values]
end
end
http://ruby-doc.org/core-2.0.0/doc/syntax/calling_methods_rdoc.html#label-Array+to+Arguments+Conversion
Values from mltiple columns with same name from csv
# file.csv
name,name
one,two
Because you cannot use []
method to access all the duplicate columns, you can just break it up into an Array
>> csv = CSV.table('file.csv')
# if you just need the values
>> csv.to_a.last
=> ["one", "two"]
# if you need to know the column name call to `to_a` on each row
>> csv.flat_map(&:to_a)
=> [[:name, "one"], [:name, "two"]]
# to aggregate duplicate column values (assuming you know the duplicate column name ahead of time)
>> csv.map{|row| row.inject({names: []}){|h,(column,value)| h[:names] << value if column == :name; h }}
=> [{:names=>["one", "two"]}]
Using Ruby CSV to extract one column
To pluck a column out of a csv I'd probably do something like the following:
col_data = []
CSV.foreach(FILENAME) {|row| col_data << row[COL_INDEX]}
That should be substantially faster than any operations on CSV.Table
Rails: How to add data header in csv file if different attributes are there in Json?
You will need to collect all available keys first and then get the values for those keys in the same order for each hash.
user_hash = JSON.parse(user.to_json)
keys = user_hash.flat_map(&:keys).uniq
CSV.open(file, 'w') do |csv|
csv << keys
user_hash.each { |hash| csv << hash.values_at(*keys) }
end
Related Topics
How to Debug Http of Ruby Google-Api-Client
Replacing Text in One CSV Column Using Fastercsv
Message Queues in Ruby on Rails
Ruby Method Calls Declared in Class Body
In Ruby, What Is the Cleanest Way of Obtaining the Index of the Largest Value in an Array
Restoring Rails 3's Bundle Install Path... It's Now Install in My Root
Puppet/Facter "Could Not Retrieve Fact Fqdn": How to Fix or Circumvent
Guidelines for Where to Put Classes in Rails Apps That Don't Fit Anywhere
Does Dependency Injection Exist in Rails
How to Call Java API from Ruby 1.8 or 1.9
Why Doesn't 'User Installation Directory' Match with the Ruby Version
How to List All Versions of a Gem Available at a Remote Site
When Do We Use the "||=" Operator in Rails? What Is Its Significance
Rails 3/Ruby: Activerecord Find Method in Condition Array to Parameters Single Quote Issue