Bangs
Learn about the bang methods in Ruby.
We'll cover the following
Bang methods
All the examples we’ve discussed before are questions and don’t modify the object they’re called on.
name = "Ruby Monstas"puts name.downcaseputs name
If we run the lines of code above, the downcase
method returns a new lowercase version of the original string. When we output the original string on the next line, we can then see that it’s still the same. The downcase
method doesn’t modify the string.
Methods ending with !
However, there are also variants of some of these methods that end in an exclamation mark (!
). These are called bang methods, and they usually modify the object they’re called on.
For example, in addition to the method, downcase
strings also have a downcase!
method.
Let’s try that:
name = "Ruby Monstas"puts name.downcase!puts name
Notice that calling the downcase!
method on the second line modifies the string itself (the object that name
refers to) and also returns the new lowercase version.
Nowadays, programmers have learned that using these methods has a number of disadvantages and should usually be avoided unless there are very good reasons for it (usually, there are none).
Remember: Use bang methods with caution.
We’ve learned about them here, though, because you might see them used elsewhere.