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"]
]

5 Answers 5

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"]]
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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.
2

More of the same:

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

Ruby is fun stuff!

Comments

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

Comments

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.

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.