Ruby and its destructive methods…

In ruby there are methods followed by a “!” symbol (exclamation mark). These methods alter the object itself.

For example in the Array class there are two versions of shuffle method
shuffle and shuffle!.

a = [1,2,3, 4] => [1, 2, 3, 4]
a.object_id => 70279519801380
a.shuffle.object_id => 70279519867040
a.shuffle!.object_id => 70279519801380

  • Shuffle version returns a new array with elements of self shuffled and as a.shuffle.object_id shows a different value from a.object_id.
  • shuffle! modifies the object itself,  shuffling elements in self in place and a.shuffle!.object_id shows the same object_id of a.object_id.

Leave a Reply

Your email address will not be published.

*