Ruby - What's the difference between a method with and without an exclamation point?

StackOverflow https://stackoverflow.com/questions/23556052

  •  18-07-2023
  •  | 
  •  

Question

For example, I've checked the documentation on certain methods, like sort. And it looks like the only difference between .sort and .sort! is that one sorts self in place and the other returns an array. I'm a little unclear on what that means - they seem to effectively do the same thing.

Can anyone help me understand this a little better?

Was it helpful?

Solution

When to Use Bang Methods

Technically, the exclamation point (or bang) doesn't intrinsically mean anything. It's simply an allowable character in the method name. In practice, however, so-called bang methods generally:

  • Changed objects in-place. For example, #sort! sorts self in place, while #sort returns a new array created by sorting self.

  • Some bang methods return nil if no changes were made, which can cause problems with method chains. For example:

    'foo'.sub 'x', 'y'
    # => "foo"
    'foo'.sub! 'x', 'y'
    #=> nil
    

Use bang methods when you want to mark a method as creating notable side effects, producing destructive operations, or otherwise requiring additional caution or attention. This is largely by convention, though, and you could make all your methods bang methods if you were so inclined.

OTHER TIPS

Methods with a bang(!) are meant to signify a little more caution is required. So, either modification in place vs. not in place (if you are modifying the object in place - you better be sure that you really want to), or in other cases like find_by and find_by! (see here) where one causes an exception if no record is found and one doesn't cause an exception.

Can you guess which one does and which one does not cause an exception?

The methods with the exclamation point alter the actual object they're called on, where as the methods without will just return a new object that has been manipulated. i.e.

pizza = 'pepperoni'
pizza.capitalize

Now the pizza variable will still equal 'pepperoni'. If we then call

pizza.capitalize!

The pizza variable will now equal 'Pepperoni'

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top