Does giving a
idea = gets.reverse
print idea
If user inputted 'dog' it would come out 'dog'
But if you did this code...
idea = gets.reverse!
print idea
Then the string variable being returned would be 'god', right?
Does giving a
idea = gets.reverse
print idea
If user inputted 'dog' it would come out 'dog'
But if you did this code...
idea = gets.reverse!
print idea
Then the string variable being returned would be 'god', right?
Why not try it:
irb(main):001:0> idea = gets.reverse
dog
=> "\ngod"
irb(main):002:0> idea = gets.reverse!
dog
=> "\ngod"
Both will return the reversed string. However:
irb(main):010:0> idea = gets
dog
=> "dog\n"
irb(main):011:0> idea.reverse
=> "\ngod"
irb(main):012:0> idea
=> "dog\n"
irb(main):013:0> idea.reverse!
=> "\ngod"
irb(main):014:0> idea
=> "\ngod"
reverse! will modify the current string while reverse will return a new one.
Why the "print idea" ? The gets methods asks a user for it's input. No other arguments are required.
In that case, whether you're using reverse or reverse! wouldn't change anything. The reverse method reverses the string and returns the reversed one. The reverse! method reverses the string, returns the reversed one and changes the original string to the new value.
So if you have :
str = "god"
rst = str.reverse
p rst + ' ' + str
It'll display "dog god" as the reversed string is only returned and you do not exploit the returned value.
If you have :
str = "god"
rst = str.reverse!
p rst + ' ' + str
It'll display "dog dog" as the reverse! method reverses the string, returns it and changes the original variable.
reverse
returns a new reversed string.
s = "hello"
s1 = s.reverse
puts s , s1
#=> "hello"
# "olleh"
reverse!
reverses the current string itslef and returns a reference to it.
s = "hello"
s1 = "hello".reverse!
puts s , s1
#=> "olleh"
# "olleh"
# Now check that s1 == s2 (Refrerence check)
s1[4] = "k"
puts s , s1
#=> "ollek"
# "ollek"
I think that what you're stuck on is this:
idea
?The key thing is that everything on the right happens before the assignment. So if you chain a bunch of methods on the right, then what gets assigned is the final result of the chain.
Play with it a little in irb
and see:
>> input = gets.chomp.reverse
fooboo
=> "ooboof"
>> input = gets.chomp.reverse.upcase
fooboo
=> "OOBOOF"
What might also be tripping you up is that Ruby's string method reverse
returns a reversed string, but it doesn't actually change the string it's called on. To change the string itself, as others have said, you need the reverse!
method. This is a pattern in the language. (This can be a gotcha, and there are similar gotchas in other languages. For example sort @array
in Perl returns a reversed array but doesn't change @array
's order.)