Ruby “.downcase! ” and “downcase” confusion

后端 未结 4 1982
耶瑟儿~
耶瑟儿~ 2021-01-17 06:10

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:

4条回答
  •  日久生厌
    2021-01-17 06:49

    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
    

提交回复
热议问题