What is the purpose of “!” and “?” at the end of method names?

后端 未结 5 2075
生来不讨喜
生来不讨喜 2020-12-04 07:28

Sometimes I see methods in Ruby that have \"?\" and \"!\" at the end of them, e.g:

name = \"sample_string\"
name.reverse
name.reverse!
name.is_binary_data?
<         


        
5条回答
  •  被撕碎了的回忆
    2020-12-04 07:57

    In contrast to the – I suppose – majority of programming languages ...

    Ruby, methods are allowed to end with question marks or exclamation marks.

    By convention, methods that answer questions (i.e. Array#empty? returns true if the receiver is empty) end in question marks.

    Potentially “dangerous” methods (ie methods that modify self or the arguments, exit! etc.) by convention end with exclamation marks.

    From: http://www.ruby-lang.org/en/documentation/ruby-from-other-languages/, Section Funny method names

提交回复
热议问题