0

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"]
]
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232

5 Answers5

4
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"]]
steenslag
  • 79,051
  • 16
  • 138
  • 171
3
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

avl
  • 663
  • 3
  • 6
  • The data should be treated like CSV data. Arbitrarily splitting on commas works in this case but would fail if there was an embedded comma. – the Tin Man Jan 01 '15 at 15:24
2

More of the same:

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

Ruby is fun stuff!

0

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.

Kenny Meyer
  • 7,849
  • 6
  • 45
  • 66
0

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
Jikku Jose
  • 18,306
  • 11
  • 41
  • 61