ruby - Use of the bang? -
some people bang !
indicates method "may" modify object.
in example:
foo = "a string" foo.downcase puts foo # => string foo.downcase! puts foo # => string
the bang symbol appears causing side effect. obj.method!
equivalent obj = obj.method
? if not, why? there method these 2 expressions not equivalent?
the bang ! in method name means "danger" in general.
it method naming convention, not operator, not rule.
it typically means warning, or mutation, or irreversable, or raises exception, etc.
we utilize "!" naming convention distiguish 2 similar methods:
the normal method name returns result.
the "!" method name dangerous.
made examples of "!" meaning mutation:
obj.change #=> homecoming new object has change. obj.change! #=> alter mutating object.
made examples of "!" meaning "raises error":
obj.save #=> if object can't save, homecoming false. obj.save! #=> if object can't save, raise exception.
made examples of "!" mean "danger" or "cannot undone":
obj.exit #=> exit normally, running exit handlers. obj.exit! #=> exit immediately, skipping exit handlers.
all of these naming conventions, developer has chosen provide 2 similarly-named methods.
ruby
No comments:
Post a Comment