Reverse a String Each Two Characters with Ruby

Reverse a string each two characters with Ruby

I'm not sure if this is the best way to do it:

"0123456789abcdef".scan(/../).reverse.join == "efcdab8967452301"

Ruby reverse string with unshift

split isn't doing what you think it is (by default, it splits on whitespace, not on each character):

> "Hello".split
#=> ["Hello"]

You probably want chars:

> "Hello".chars
#=> ["H", "e", "l", "l", "o"]

You can also just use the each_char method:

string.each_char do |char|

Method to reverse string only if it has less than four letters

just put puts conditional_reverse("cat") out side our def

def conditional_reverse(string)
good = string.length
if good < 4
puts string.reverse
else
puts string
end
end

conditional_reverse("cat")


Related Topics



Leave a reply



Submit