Safirah Safirah - 8 days ago 4
Ruby Question

Ruby: How to sort a string, keeping some characters in place?

I'm a newbie in Ruby and I'd like to sort a string, but keeping the non alphanumerical characters in place.
Eg:

"hello, sally! seen 10/dec/2016" => "ehllo, allsy! eens 01/cde/0126"


I've tried doing:

word.scan(/\w+/).collect { |e| ((e.scan /\w/).sort.join)}
#=> ["ehllo", "allsy", "eens", "01", "cde", "0126"]


But I can't figure out how to put the non alphanumeric characters back.

Answer

But I can't figure out how to put the non alphanumeric characters back.

It would be easier to not remove them in the first place:

str = "hello, sally! seen 10/dec/2016"

str.gsub(/\w+/) { |m| m.chars.sort.join }
#=> "ehllo, allsy! eens 01/cde/0126"

gsub scans the string for the given pattern and passes each match string to the block, replacing it with the block's result.

The block is called with "hello", "sally", "seen", "01", "dec" and "0126". It sorts the string via:

m = "hello"
m.chars #=> ["h", "e", "l", "l", "o"]
 .sort  #=> ["e", "h", "l", "l", "o"]
 .join  #=> "ehllo"

gsub then substitutes the block's result for the match.