From: Josh Cheek Date: 2011-04-24T03:33:16+09:00 Subject: Re: Reversing a string without using array, classes and reverse function --90e6ba53ac2e19075704a19a35af Content-Type: text/plain; charset=ISO-8859-1 On Thu, Apr 21, 2011 at 10:54 PM, Rubist Rohit < passionate_programmer@hotmail.com> wrote: > I am trying this: > > mystring = gets > mystring.scan(/..$/) {|x| puts x} > > It returns only the last character. Is it possible to add the above line > in loop? > > -- > Posted via http://www.ruby-forum.com/. > > Thought I'd join the fun :) s = "12345" # using reverse s.reverse # => "54321" # using each_char s2 = "" s.each_char { |char| s2 = char << s2 } s2 # => "54321" # using scan s2 = "" s.scan(/./) { |char| s2 = char << s2 } s2 # => "54321" # using unix (this doesn't escape all chars properly, though) `rev <<<#{s.inspect}`.chomp # => "54321" # using recursion rev = lambda do |string| if string.empty? "" else rev.call(string[1..-1]) << string[0,1] end end rev.call s # => "54321" # exchanging chars s2 = s.dup s2.length./(2).times { |i| s2[i] , s2[-i-1] = s2[-i-1] , s2[i] } s2 # => "54321" --90e6ba53ac2e19075704a19a35af--