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

Viewed 60

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
3 Answers

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

Here's how I'd do it:

def odd_reverse(str)
  a = [str, str.reverse]
  str.size.times.map {|i| a[i % 2][i] }.join
end

odd_reverse("hello world")
# => "hlloo wlred"

This is pretty simple. For each character index i it alternates (i % 2) taking the next char from either the string or its reverse ([s, s.reverse]).

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