How to split the content of one column into two columns of csv in Ruby?

后端 未结 1 1395
臣服心动
臣服心动 2021-01-29 14:03

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

相关标签:
1条回答
  • 2021-01-29 14:14

    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"]
    
    0 讨论(0)
提交回复
热议问题