15. Strings and Methods (Chaining)


#1

What is the purpose of chaining methods? Is there a benefit? Chaining only seems to return the last method.

Example.

name = "John"

name.downcase.reverse.upcase

When we chain the name the result would be "EOD NHOJ". It appears that the last method overrides the first method, but by chaining it would apply all methods.

In typing this I somewhat answered my own question, but I'm wondering if there's any benefits in chaining downcase.upcase since it would return all uppercase and NOT lowercase.


#2

How would you write this piece of code without chaining? Looks a lot more tedious to me:

name = "John"

name.downcase!
name.reverse!
name.upcase!

And yes, in our example it doesn't make much sense to downcase if we upcase after that. Might as well just upcase.reverse.