ruby-on-railsruby

I know how to reverse a string in ruby without .reverse, but is there a way to only reverse odd indexed characters?


I know how I can reverse a string in ruby without the reverse method

def reverse(string)
 
string.each_char.inject(""){|str, char| str.insert(0, char) }

end
puts reverse('hello world')

but is there a way I can reverse only the odd indices to look like this.

output: hlloo wlred

Solution

  • Working off of Les Nightingill's answer I came up with this which handles both odd and even length strings using the reference_index variable to point to the end of the string or slightly past it as needed.

    def funky_reverse(str)
      out = ''
      reference_index = str.length.odd? ? str.length - 1 : str.length
      str.length.times{ |i| out += i.even? ? str[i] : str[reference_index - i] }
      out
    end
    
    > funky_reverse('hello world')
    => "hlloo wlred"
    > funky_reverse('hello world!')
    => "h!lloow rlde"
    

    This looks like a homework question? :D