DEV Community

Jazmine
Jazmine

Posted on

"!" and "?" in Ruby Methods

Thanks to a meeting with a student, I learned about some neat ways Ruby improves the readability of its code!

Ruby methods ending with ! indicates that it will modify the object it's acting on.

For example, using the reverse method will return the array with the items in the reversed order. When you call the array again, it will return as it originally was.

a = ["red", "yellow", "blue", "pink"]
a.reverse 
# => ["pink", "blue", "yellow", "red"]

a = ["red", "yellow", "blue", "pink"]
Enter fullscreen mode Exit fullscreen mode

However, when you add the ! to the end of the method, it will overwrite it, and modify the array!

a = ["red", "yellow", "blue", "pink"]
a.reverse!
# => ["pink", "blue", "yellow", "red"]

a = ["pink", "blue", "yellow", "red"]
Enter fullscreen mode Exit fullscreen mode

Ruby methods ending with ? indicates that it will return a boolean.

4.odd? # => false
5.odd? # => true
6.even? # => true

Enter fullscreen mode Exit fullscreen mode

Top comments (0)