Ruby “.downcase! ” and “downcase” confusion

后端 未结 4 1947
耶瑟儿~
耶瑟儿~ 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:47

    a.downcase! modifies "a" directly -- you do not need to assign the result to "a".

    1.9.3p362 :003 > a = "A"
     => "A" 
    1.9.3p362 :004 > a.downcase!
     => "a" 
    1.9.3p362 :005 > puts a
    a
     => nil 
    1.9.3p362 :006 > a = "A"
     => "A" 
    1.9.3p362 :007 > a.downcase
     => "a" 
    1.9.3p362 :008 > puts a
    A
     => nil 
    

    The danger of assigning variable = variable.downcase! is that if variable is already downcase then you have just set the variable to nil -- probably not your intent.

    1.9.3p362 :001 > variable = 'a'                                                                                                                                                                                                                                               
     => "a"                                                                                                                                                                                                                                                                       
    1.9.3p362 :002 > variable = variable.downcase!
     => nil                                                                                                                                                                                                                                                                       
    1.9.3p362 :003 > puts variable                                                                                                                                                                                                                                                
    
     => nil 
    

提交回复
热议问题