views:

144

answers:

3

Let's say I have this string:

"birthday cake is my favorite"

I need to convert that to:

"birthday|cake|is|my|favorite"

How would I go about doing that with Ruby?

+7  A: 

Always nice to be able to answer not using a regex :-)

your_string.split(" ").join("|") 

should do it.

DanSingerman
Use split(/[^\w]+/).join("|") if you want all non-word characters stripped out."birthday cake: my favorite".split(/[^\w]+/).join("|") #=> "birthday|cake|my|favorite"EDIT: Ha, just saw your comment about not using a regex. Makes my comment a little ironic.
Adam Stegman
Bonus points for handling multiple spaces out of the box!
jerhinesmith
+7  A: 
"birthday cake is my favorite".gsub(" ", "|")
Trevor
you might want `.gsub(/ +/,"|")` to combine multiple spaces into one pipe char.
AShelly
I'd use \s+ - using a literal blank for whitespace in a regex bothers me for some reason.
klochner
+5  A: 

This is precisely what String#tr (and String#tr_s) is for:

# Look, Ma! No Regexp!
'birthday cake is my     favorite'.tr_s(' ', '|')
# => "birthday|cake|is|my|favorite"

I admit, the method names aren't the most intuitive. (Unless you are a Mac OSX, Unix, Linux, Cygwin or MinGW user, of course, in which case tr and tr -s will be part of your daily arsenal.)

Jörg W Mittag