Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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!

share|improve this question

1 Answer

up vote 3 down vote accepted

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.

share|improve this answer
I like it, I like it!! Thanks Flambino! – SteveO7 Apr 19 at 11:37
I knew there was an elegant "Ruby" way to do this! – SteveO7 Apr 19 at 12:30
@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 :) – Flambino Apr 19 at 13:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.