Predicate and Bang Methods

Ruby allows you to use non-alphanumeric characters in method names. There are a couple that are used fairly commonly: ? and !

You put the character at the end of the method name.

Predicate

? indicates a “predicate” method. This is a method that returns true or false. So, for example, if you want to know if the result of a particular operation is true or false, you can create a method that does that operation, then returns true or false based on the result of the operation.

For example, if you want to know if the player won a game, you could make a method called “won?”

Then use it like:

if won?
   puts “Congratulations, you won!”
else
   puts “Sorry, you lost.”

It’s a great way to make code that almost reads like English.

Bang

A bang method tells you that this method does something “dangerous” (changes a value, dun, dun, duu-uu-un).

def turns_remaining!
   @turns_remaining -= 1 # decrements variable
end

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Skip to content