Reputation: 11
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.
Upvotes: 1
Views: 86
Reputation: 35731
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
Upvotes: 0
Reputation: 10472
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
Upvotes: 4