I got an object of CSV, the content is like:
full_name | phone_number |
Mike Smith | (123)-456-7890|
Tony Davis | (213)-564-7890|
And I would
So far the question doesn't make enough sense so I expect it'll be closed eventually. Here's some information about how to split the fields so that, maybe, we can get to the real root of the problem.
Meditate on this:
ary = <<EOT
full_name | phone_number |
Mike Smith | (123)-456-7890|
Tony Davis | (213)-564-7890|
EOT
PIPE_DELIMITER = /\s*\|\s*/
munged_data = ary.lines[1..-1].map { |l|
full_name, phone_number = l.split(PIPE_DELIMITER) # => ["Mike Smith", "(123)-456-7890"], ["Tony Davis", "(213)-564-7890"]
first_name, last_name = full_name.split # => ["Mike", "Smith"], ["Tony", "Davis"]
[first_name, last_name, phone_number]
}
# => [["Mike", "Smith", "(123)-456-7890"], ["Tony", "Davis", "(213)-564-7890"]]
At this point it's possible to generate some usable CSV data:
require 'csv'
CSV.open("/dev/stdout", "wb") do |csv|
csv << %w[first_name last_name phone_number]
munged_data.each do |row|
csv << row
end
end
Which results in:
# >> first_name,last_name,phone_number
# >> Mike,Smith,(123)-456-7890
# >> Tony,Davis,(213)-564-7890
Note the use of a regular expression as a parameter to split
; This tells split
to clean up the resulting output a bit by only splitting on zero-or-more whitespace delimited by |
:
PIPE_DELIMITER = /\s*\|\s*/
full_name, phone_number = l.split('|') # => ["Mike Smith ", " (123)-456-7890", "\n"], ["Tony Davis ", " (213)-564-7890", "\n"]
full_name, phone_number = l.split(PIPE_DELIMITER) # => ["Mike Smith", "(123)-456-7890"], ["Tony Davis", "(213)-564-7890"]
At that point it is easy to split the names:
first_name, last_name = full_name.split # => ["Mike", "Smith"], ["Tony", "Davis"]