Question

I would like to pass a sequence of characters into a function as a string and have it return to me that string split at the following characters:

@ # $ % ^ & *

such that if the string is

'hey#man^you*are#awesome'

the program returns

'hey man you are awesome'

How can I do this?

Was it helpful?

Solution

To split the string you can use String#split

'hey#man^you*are#awesome'.split(/[@#$%^&*]/)
#=> ["hey", "man", "you", "are", "awesome"]

to bring it back together, you can use Array#join

'hey#man^you*are#awesome'.split(/[@#$%^&*]/).join(' ')
#=> "hey man you are awesome"

split and join should be self-explanatory. The interesting part is the regular expression /[@#$%^&*]/ which matches any of the characters inside the character class [...]. The above code is essentially equivalent to

'hey#man^you*are#awesome'.gsub(/[@#$%^&*]/, ' ')
#=> "hey man you are awesome"

where the gsub means "globally substitute any occurence of @#$%^&* with a space".

OTHER TIPS

You could also use String#tr, which avoids the need to convert an array back to a string:

'hey#man^you*are#awesome'.tr('@#$%^&*', '       ')
  #=> "hey man you are awesome" 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top