Why are exclamation marks used in Ruby methods?

后端 未结 10 2065
小蘑菇
小蘑菇 2020-11-22 06:01

In Ruby some methods have a question mark (?) that ask a question like include? that ask if the object in question is included, this then returns a

10条回答
  •  有刺的猬
    2020-11-22 06:20

    Simple explanation:

    foo = "BEST DAY EVER" #assign a string to variable foo.
    
    => foo.downcase #call method downcase, this is without any exclamation.
    
    "best day ever"  #returns the result in downcase, but no change in value of foo.
    
    => foo #call the variable foo now.
    
    "BEST DAY EVER" #variable is unchanged.
    
    => foo.downcase! #call destructive version.
    
    => foo #call the variable foo now.
    
    "best day ever" #variable has been mutated in place.
    

    But if you ever called a method downcase! in the explanation above, foo would change to downcase permanently. downcase! would not return a new string object but replace the string in place, totally changing the foo to downcase. I suggest you don't use downcase! unless it is totally necessary.

提交回复
热议问题