1

I try to implement my own reverse string method:

def string_reverse(string)
  half = string.length / 2
  half.times do |i|
    string[i] = string[-i-1]
    string[-i-1] = string[i]
  end
end

But it only reverses the first half of the string. What am i missing here?

1
  • 2
    For problems like this, it helps to go step-by-step, with paper, through an imaginary use case. Eg, "the string is 'hi there', length 8, so half is 4. The first time through the loop, i is 0, so I set string[0] to be string[-0-1], which is -1...." Go all the way through for one example string and see if each step makes sense and what the string would be after that step. Some very simple test cases would help you, too: fail "couldn't reverse foo, got #{string_reverse('foo')}" unless string_reverse("foo") == "oof" Commented Mar 5, 2015 at 10:54

2 Answers 2

6

You need a third variable to swap the characters, or use parallel assignment:

def string_reverse(string)
  half = string.length / 2
  half.times do |i|
    string[i], string[-i-1] = string[-i-1], string[i]
  end
end
Sign up to request clarification or add additional context in comments.

Comments

1
def string_reverse(string)
  half = string.length / 2
  half.times do |i|
    x = string[i]
    string[i] = string[-i-1]
    string[-i-1] = x
  end
end

1 Comment

Baldrick answer is perfect :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.