Why puts for .upcase .downcast but not for .lenght?


#1

Im just trying to understand the concept rather then memorizing it.
Why do I need to use put for .upcase .downcase but for .reverse and .length is not required.
Thank you


#2

puts (short for put string) is only needed if we wish to send output to the screen. We are not required to print.

The string methods .upcase, .downcase, .reverse and .length do not alter the string upon which they are invoked. Rather, a temporary object is created (except for .length) and the modifications made on a copy. We can either directly print, or store the new string.

a = "somestring"
b = a.upcase
c = b.downcase
d = b.reverse

puts d    #->  GNIRTSEMOS

As we’ve seen, the methods create a copy, modify it and then return the copy. Ruby permits these same methods to overwrite the variable they are called upon. The ! modifier (the bang) signifies in-place mutation. It still uses a temporary object which is a copy of the value. It then applies the method to the temporary object and if any change takes place, replaces the value with the mutated string.

The kicker here is that if no change occurs, the return is nil. The NB here is that we must be certain when using the bang that some change is guaranteed if we expect to call any methods on the return value.

Let’s look at an example that uses method chaining and the bang so all changes are in-place…

 > a.downcase!.reverse!
undefined method `reverse' for nil:NilClass
(repl):1:in `<main>'
 > b.downcase!.reverse!
=> "gnirtsemos" 
 > puts b
 gnirtsemos
 > 

Note that in the first example, no change occurs, so the return is nil. nil has no methods or attrbutes.

The second example works because there is a mutation of the string object so a string remains.


#3

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