Why are exclamation marks used in Ruby methods?

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

    From themomorohoax.com:

    A bang can used in the below ways, in order of my personal preference.

    1) An active record method raises an error if the method does not do what it says it will.

    2) An active record method saves the record or a method saves an object (e.g. strip!)

    3) A method does something “extra”, like posts to someplace, or does some action.

    The point is: only use a bang when you’ve really thought about whether it’s necessary, to save other developers the annoyance of having to check why you are using a bang.

    The bang provides two cues to other developers.

    1) that it’s not necessary to save the object after calling the method.

    2) when you call the method, the db is going to be changed.

    http://www.themomorohoax.com/2009/02/11/when-to-use-a-bang-exclamation-point-after-rails-methods

提交回复
热议问题