How do you reverse a string in Ruby? I know about string#reverse. I\'m interested in understanding how to write it in pure Ruby, preferably an in-place solution.
Here's one way to do it with inject and unshift:
"Hello world".chars.inject([]) { |s, c| s.unshift(c) }.join
"abcde".chars.reduce{|s,c| c + s } # => "edcba"
A simple classic way with n/2 complexity
str = "Hello World!";
puts str;
for i in 0..(str.length/2).to_i
mid = (str.length-1-i);
temp = str[i];
str[i] = str[aa];
str[aa] = temp;
end
puts str;
Here's an alternative using the xor bitwise operations:
class String
def xor_reverse
len = self.length - 1
count = 0
while (count < len)
self[count] ^= self[len]
self[len] ^= self[count]
self[count] ^= self[len]
count += 1
len -= 1
end
self
end
"foobar".xor_reverse
=> raboof
def reverse(string)
reversed_string = ""
idx = 0
while idx < string.length
reversed_string = string[idx] + reversed_string
idx += 1
end
return reversed_string
end
def palindrome(string)
s = string.gsub(/\W+/,'').downcase
t = s.chars.inject([]){|a,b| a.unshift(b)}.join
return true if(s == t)
false
end