Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Array's pop method not have an exclamation mark?

Tags:

ruby

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!?

like image 877
Cameron Martin Avatar asked Jun 19 '12 19:06

Cameron Martin


2 Answers

"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.)

like image 29
steenslag Avatar answered Nov 03 '22 00:11

steenslag


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.

like image 61
megas Avatar answered Nov 02 '22 22:11

megas