Why are exclamation marks used in Ruby methods?

后端 未结 10 2173
小蘑菇
小蘑菇 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:21

    Bottom line: ! methods just change the value of the object they are called upon, whereas a method without ! returns a manipulated value without writing over the object the method was called upon.

    Only use ! if you do not plan on needing the original value stored at the variable you called the method on.

    I prefer to do something like:

    foo = "word"
    bar = foo.capitalize
    puts bar
    

    OR

    foo = "word"
    puts foo.capitalize
    

    Instead of

    foo = "word"
    foo.capitalize!
    puts foo
    

    Just in case I would like to access the original value again.

提交回复
热议问题