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?
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?
Always nice to be able to answer not using a regex :-)
your_string.split(" ").join("|")
should do it.
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.)