0
\$\begingroup\$

I need to add quotes to each word in a string. Here is something that works but it looks ugly to me;

"this is a test".split.to_s.delete("[],")

produces

"\"this\" \"is\" \"a\" \"test\""

split adds the quotes, to_s turns the array back to a string, then the delete removes the array stuff. The downside is the case where the data includes [] or ,

I welcome your responses!

asked Apr 18, 2013 at 22:41
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

Here's the "naïve" way to go

"this is a test".split.map { |word| "\"#{word}\"" }.join(" ")

But a better way is to use a regular expression, since those are made specifically for string manipulation/substitution

"this is a test".gsub(/\S+/, '"0円"')

The expression matches 1 or more (the +) non-whitespace characters (the \S) in a row, and replaces the match with the same string (the 0円) but surrounded by quotes.

answered Apr 18, 2013 at 23:38
\$\endgroup\$
2
  • \$\begingroup\$ I knew there was an elegant "Ruby" way to do this! \$\endgroup\$ Commented Apr 19, 2013 at 12:30
  • \$\begingroup\$ @SteveO7 Well, it's not terribly specific to Ruby; tons of languages and tools support regular expressions because they're so useful. Syntaxes and APIs vary slightly, but the gist is the same. E.g. the here's the pretty much same using the sed *nix command: echo 'this is a test' | sed 's/[^ ]*/"&"/g'"this" "is" "a" "test". Point is, regexps are neat :) \$\endgroup\$ Commented Apr 19, 2013 at 13:34

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.