1

I have a string from tab delimited file (with carriage return and newline)

"a\taa\taaa\r\nb\tbb\tbbb\r\nc\tcc\tccc"

I want to convert this string into an array like

[["a","aa","aaa"],["b","bb","bbb"],["c","cc","ccc"]]

Now I already did .scan(/(.+?)\r\n/) but I still got only

[["a\taa\taaa"],["b\tbb\tbbb"],["c\tcc\tccc"]]
1
  • This sounds like an XY Problem. How are you getting the string? Using the CSV class should make this very easy. Commented Jan 23, 2017 at 18:10

2 Answers 2

5

I tend to use CSV#parse for things like this, since the parsing code is easy to understand:

CSV.parse("a\taa\taaa\r\nb\tbb\tbbb\r\nc\tcc\tccc", col_sep: "\t")
=> [["a", "aa", "aaa"], ["b", "bb", "bbb"], ["c", "cc", "ccc"]]
Sign up to request clarification or add additional context in comments.

Comments

1

How about using String#split and Array#map?

s = "a\taa\taaa\r\nb\tbb\tbbb\r\nc\tcc\tccc"

s.split("\r")  # split by \r (bigger chunks)
=> ["a\taa\taaa", "\nb\tbb\tbbb", "\nc\tcc\tccc"]

s.split("\r").map { |x| x.split }  # Split bigger chunks by spaces (including \t)
=> [["a", "aa", "aaa"], ["b", "bb", "bbb"], ["c", "cc", "ccc"]]

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.