1

I have this kind of data in my csv file,

Albany, N.Y.
Albuquerque, N.M.
Anchorage, Alaska
Asheville, N.C.
Atlanta, Ga.
Atlantic City, N.J.
Austin, Texas
Baltimore, Md.
Baton Rouge, La.
Billings, Mont.
Birmingham, Ala.
Bismarck, N.D.
Boise, Idaho
Boston, Mass.
Bridgeport, Conn.

I want to convert it into this form:

Albany, N.Y.;Albuquerque, N.M.;Anchorage, Alaska;Asheville, N.C.;Atlanta, Ga.;Atlantic City, N.J.;Austin, Texas;Baltimore, Md.;Baton Rouge, La.;Billings, Mont.;Birmingham, Ala.;Bismarck, N.D.;Boise, Idaho;Boston, Mass.;Bridgeport, Conn.

What I have got so far:

require 'csv'

CSV.foreach("test.csv") do |row|
  puts row.inspect
end

But instead of getting a full row, it's just giving arrays, separated over coma? How is it possible to convert it in this manner?

1
  • With no quoting, you could just do File.open(fn).read.split(/\n/).join(';') Commented Aug 12, 2017 at 4:27

3 Answers 3

1

Do you want only to read and print the data?, you could try using map and join:

p CSV.foreach('test.csv').map(&:join).join(';')
# => "Albany N.Y.;Albuquerque N.M.;Anchorage Alaska;Asheville N.C.;Atlanta Ga ...
Sign up to request clarification or add additional context in comments.

Comments

1

The following should do it:

require 'csv'

result = Array.new
CSV.foreach('test.csv') do |row|
  result << row.join(',')
end
puts result.join(';')

Comments

1

There's no benefit to using the CSV class here. Just treat it like a regular text file.

File.read('test.csv').gsub('\n', ';')
  #=> "Albany N.Y.;Albuquerque N.M.;Anchorage Alaska;..."

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.