Confused on "string and string method"


#1

https://www.codecademy.com/en/courses/ruby-beginner-en-d1Ylq/3/3

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?


#2

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.

new_string.reverse!
puts new_string                         # GNIRTS A SI SIHT

Watch what happens here...

new_string.downcase
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

old_string.reverse!
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, !.

new_string.downcase.reverse.upcase!

Ignore the redundancy and take it as an example.


#3

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


#4

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