简体   繁体   中英

String with comma-separated values and newlines: split values and create arrays for each newline

I have a string like this (from a form submission):

"apple, banana\r\ncherries\r\n\r\ngrapes, blue berries \r\n\r\n \r\norange"

How do I detect values AND create an array for each line that has text? Like this:

[
  ["apple", "banana"],
  ["cherries"],
  ["grapes", "blue berries"],
  ["orange"]
]
require "csv"

str = "apple, banana\r\ncherries\r\n\r\ngrapes, blue berries \r\n\r\n \r\norange"

rows = CSV.parse(str, skip_blanks: true)
rows = rows.map{|row| row.map(&:strip)} # remove leading and trailing whitespace
rows.delete([""]) 

p rows # => [["apple", "banana"], ["cherries"], ["grapes", "blue berries"], ["orange"]]
s = "apple, banana\r\ncherries\r\n\r\ngrapes, blue berries \r\n\r\n \r\norange"
s.each_line.reject { |l| l =~ /^\s+$/ }.map { |l| l.strip.split(', ') }

There is definitely something shorter

More of the same:

s.each_line.map { |l| l.strip.split(', ') }.reject(&:empty?)

Ruby is fun stuff!

You can try this:

a = "apple, banana\r\ncherries\r\n\r\ngrapes, blue berries \r\n\r\n \r\norange"
a.gsub("\r", "").each_line.map{|d| d.strip.split(",")}.reject(&:empty?)

...and you can definitely refactor this.

Try this?

s = "apple, banana\r\ncherries\r\n\r\ngrapes, blue berries \r\n\r\n \r\norange"

result = s.split(/[\r\n]+/).map do |match|
  next unless match =~ /\w/
  match.strip.split(/,\s?/)
end

result.compact # => [["apple", "banana"], ["cherries"], ["grapes", "blue berries"], ["orange"]]

If terse is better:

s.split(/[\r\n]+/).map { |m| next unless m =~ /\w/; m.strip.split(/,\s?/) }.compact

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM