I just started Ruby programming. I had read Difference Between downcase and downcase! in Ruby. However I encounter an interesting problem in practice, here is code:
downcase!
is a method which modifies the string in-place (whereas downcase
creates a new string instance).
The return value of downcase!
is nil
if the string has not been modified, or the new modified string. In the latter case the string in a
gets overwritten. The correct way of using downcase!
is:
a = "LOWER"
a.downcase! # no assignment to a here
print a # prints "lower", the original "LOWER" is lost
And for downcase
:
a = "LOWER"
print a.downcase # a is still "LOWER", but "lower" gets printed
As a general rule of thumb: If a methods ends with !
, the method overwrites values or modifies state in your variables.
Additionally in your case:
print "lower".downcase! # prints nil, because "lower" is already written in lower case