1

I'm working on a coding challenge practice problem that is asking me to put together a method that reverses a string and have come up with:

def reverse(string)
   idx = 1
   array_s = []
    while idx <= string.length
        array_s.push(string[string.length - idx])
        idx = idx + 1
    end    
    new_string = array_s.join("")
    puts new_string
end

When I run the test given at the end,

puts(
  'reverse("abc") == "cba": ' + (reverse("abc") == "cba").to_s
)
puts(
  'reverse("a") == "a": ' + (reverse("a") == "a").to_s
)
puts(
  'reverse("") == "": ' + (reverse("") == "").to_s
)

it seems to show that the strings reverse, but it still prints false. Is there anything I'm missing in the method I wrote? Thanks.

2 Answers 2

4

Your function is working as expected, it is the last line that is causing you issues.

puts new_string

puts returns nil, ruby uses implicit returns unless you explicitly say return, so it returns the result from the last line of code, in this case is nil.

If you just do new_string or return new_string, it will work.

Or if you want to print it to the screen and return it as the result, you can do

p new_string
Sign up to request clarification or add additional context in comments.

1 Comment

p new_string will return the argument, which is the string, but it does a little bit more than also print to the screen. It uses inspect and so it will also show the quotes around it. p is not a shortcut for puts.
0

davidhu2000 has answered your question correctly but i would suggest refactoring the code:

f = "forward"

puts f.reverse 

# drawrof

of if you really want:

def reverse(string)
   return string.reverse
end

Comments

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.