Home > Enterprise >  I know how to reverse a string in ruby without .reverse, but is there a way to only reverse odd inde
I know how to reverse a string in ruby without .reverse, but is there a way to only reverse odd inde

Time:09-02

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

CodePudding user response:

that's an interesting problem, here's what I came up with:

def funky_reverse(str)
  out = ""
  str.length.times{|i| out = i.even? ? str[i] : str[-i-1]}
  out
end

CodePudding user response:

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

  • Related