Reputation: 3744
I want to split the original file by 2 delimiters, comma and colon, and then store the split file separately. My program is this:
require 'csv'
CSV.open('SplitFile.csv', "wb") do |csv|
CSV.foreach('Original.csv') do |row|
csv<<row.split(/[,:]/)
end
end
But I get this error: undefined method 'split' for #<Array:0x363d0e0> (NoMethodError)
. Why is that?
EDIT: I got it to work using the following:
require 'csv'
CSV.open('SplitFile.csv', "wb") do |csv|
f = File.open('Original.csv', "r")
f.each_line { |line|
row = line.split(/[,:]/)
csv << row
}
end
Thanks to the answerers. Their methods work too.
Upvotes: 2
Views: 9203
Reputation: 8821
Because row
is an Array, not a String.
For example:
cat mycsv.csv
row,of,CSV,data
row,of,CSV,data
row,of,CSV,data
row,of,CSV,data
CSV.foreach('mycsv.csv') do |row|
puts row.inspect
end
=>
["row", "of", "CSV", "data"]
["row", "of", "CSV", "data"]
["row", "of", "CSV", "data"]
["row", "of", "CSV", "data"]
I don't know what is the contents of Original.csv
file, but I think you can do like this:
row.first.split(/[,:]/)
Upvotes: 0
Reputation: 380
Split it's method for String's
You can try something like row.map{|s|s.split(/[,:]/)}
Upvotes: 4