Confused on "string and string method"


Please note that I am a complete noob to Ruby and programming in general.

Taking that into account I am confused on the "string and string method" lesson. The instructions tell you to assign "name".downcase.reverse.upcase which I have done and end up with "EMAN" as the output which is what the lesson required.

My question is: What is the point of putting the ".downcase" in the string if only the ".reverse" and the ".upcase" method are shown in the final result?


name = "Wee Gillis".downcase.reverse.upcase
puts name

The lesson demonstrates what is generally known as method chaining. Each method executes and updates the state of the string, or returns a new string. This then becomes the execution context of the next method in the chain. The proviso is that they must be methods of the parent class, String, or of Object, the parent of String.

Ruby lets us decide whether the method returns a new string, or changes the state of the context object (the String instance).

new_string = "this is a string".upcase
puts new_string                         # THIS IS A STRING

.upcase returned a new string in this method call. To change the state directly on the string object we add ! to the method call.

puts new_string                         # GNIRTS A SI SIHT

Watch what happens here...

puts new_string                         # GNIRTS A SI SIHT

Nothing. The state has not changed. But the updated state is in the return value:

old_string = new_string.downcase
puts old_string                         # gnirts a si siht

puts old_string                         # this is a string

If we're chaining methods and only wish to change the state, then the last method in the chain is one to which will be added the modifier, !.


Ignore the redundancy and take it as an example.


Thank you! This makes it easier to understand. :slight_smile:


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.