What is Bang Method in Ruby: Explanation and Examples
bang method is a method whose name ends with an exclamation mark !. It usually means the method performs a more dangerous or permanent action, often modifying the object it is called on instead of returning a new one.How It Works
In Ruby, methods that end with an exclamation mark ! are called bang methods. This mark is a signal to the programmer that the method behaves differently from its non-bang version. Usually, a bang method changes the object it is called on directly, instead of creating and returning a new object.
Think of it like editing a document: a normal method is like making a copy of the document and changing the copy, leaving the original safe. A bang method is like editing the original document itself, which can be faster but riskier if you want to keep the original unchanged.
Not all bang methods modify objects, but by convention, they warn you that the method might have side effects or be more 'dangerous' than its non-bang counterpart.
Example
This example shows the difference between a normal method and its bang version using strings. The normal method upcase returns a new string in uppercase, while upcase! changes the original string.
str = "hello" new_str = str.upcase puts str # original string puts new_str # new string from upcase str.upcase! puts str # original string changed by upcase! method
When to Use
Use bang methods when you want to change the original object directly and are sure you don't need to keep the original unchanged. This can save memory and improve performance.
For example, when cleaning up data in place or updating a large string or array, bang methods are handy. However, if you want to keep the original data safe, use the non-bang version.
Bang methods also help signal to other programmers that the method might have side effects, so they can be more careful when using it.
Key Points
- Bang methods end with
!and usually modify the object they are called on. - They are more "dangerous" because they change data in place.
- Non-bang methods usually return a new object without changing the original.
- Not all bang methods modify objects, but they warn about side effects.
- Use bang methods when you want to save memory or explicitly change the original object.