I thought that by convention, only methods with an exclamation mark altered the object.
> array = [1, 2, 3]
=> [1, 2, 3]
> array.pop
=> 3
> array
=> [1, 2]
Why isn't Array
's pop
method called pop!
?
"The second convention is that any method whose name ends with an exclamation mark should be used with caution.(...) Often, methods that end with an exclamation mark are mutators, which alter the internal state of an object. But this is not always the case; there are many mutators that do not end with an exclamation mark , and a numbere of nonmutators that do. Mutating methods (such as Array.fill
) that do not have a nonmutating variant do not typically have an exclamation point (sic)."
(The Ruby Programming Language, Flanagan &Matsumoto, page 180)
The book continues with the example exit
versus exit!
(both nonmutating; exit!
skipping all at_exit hooks.)
That's not quite correct.
From The Ruby Style Guide
The names of potentially "dangerous" methods (i.e. methods that modify self or the arguments, exit! (doesn't run the finalizers like exit does), etc.) should end with an exclamation mark if there exists a safe version of that dangerous method.
And the name of pop method says exactly what it is doing so there's no need to sign it with exclamation mark.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With