1

I am trying to learn ruby. What is an elegant way to convert '"abcd" "efg"' to a ['abcd', 'efg'] in Ruby?

Thanks.

3 Answers 3

3

Try this:

require 'shellwords'
'"abcd" "efg"'.shellsplit
#=> ["abcd", "efg"]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! What can I use in Ruby 1.8.7?
1

You can also do it by removing " character and then splitting by space

'"abcd" "efg"'.tr('"','').split
'"abcd" "efg"'.delete('"').split

Comments

0

You can use scan which finds all occurrences of a pattern within a string.

'"aaa" "bbb"'.scan(/"([^"]*)"/)
=> [["aaa"], ["bbb"]]

Explained:

  • / something/ is a regular expression (which can match strings)
  • /" something "/ is a regular expression that matches strings starting and ending in "
  • [^"] matches against any character that isn't a "
  • [^"]* matches as many of these characters as it can.
  • The ( and ) tell it want the bits I want in the results.

1 Comment

Note: This doesn't deal with escaped " characters.

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.