Search code examples
rubystringreversemove

How to move characters from right to left of string


I need to move characters from left to right of a string in combinations of two. An example input is:

"D21635D486450000C1"

The expected output for this is:

"C100004586D43516D2"

Any help is greatly appreciated.

I have this so far:

str = "D21635D486450000C1"
str.length.times do |i|
 str.insert(i, str[-2-i])
end
puts str

Solution

  • "D21635D486450000C1".chars.each_slice(2).to_a.reverse.join
    #⇒ "C100004586D43516D2"
    

    or use join(' ') on the last step to have spaces or whatever between slices.


    Also:

    str = "D21635D486450000C1"
    (0..str.length-1).step(2).map { |i| [str[-i-2], str[-i-1]] }.join
    #⇒ "C100004586D43516D2"