Why are exclamation marks used in Ruby methods?

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

    It is most accurate to say that methods with a Bang! are the more dangerous or surprising version. There are many methods that mutate without a Bang such as .destroy and in general methods only have bangs where a safer alternative exists in the core lib.

    For instance, on Array we have .compact and .compact!, both methods mutate the array, but .compact! returns nil instead of self if there are no nil's in the array, which is more surprising than just returning self.

    The only non-mutating method I've found with a bang is Kernel's .exit! which is more surprising than .exit because you cannot catch SystemExit while the process is closing.

    Rails and ActiveRecord continues this trend in that it uses bang for more 'surprising' effects like .create! which raises errors on failure.

提交回复
热议问题