How to Create a Copy of Some Columns of a CSV File in Ruby with Different Data in One Column

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



Leave a reply



Submit