0
0
Rubyprogramming~5 mins

Method naming conventions (? and ! suffixes) in Ruby

Choose your learning style9 modes available
Introduction

These suffixes help you understand what a method does just by its name. They make your code easier to read and safer to use.

When you want to create a method that answers a yes/no question.
When you want to show a method might change the object it is called on.
When you want to warn users that a method is 'dangerous' or has side effects.
When you want to make your code clearer and easier to understand for others.
Syntax
Ruby
def method_name?
  # returns true or false
end

def method_name!
  # modifies the object or is 'dangerous'
end

Methods ending with ? should always return true or false.

Methods ending with ! usually change the object or do something risky.

Examples
This method checks if something is empty and returns true or false.
Ruby
def empty?
  @items.empty?
end
This method tries to save data and will raise an error if it cannot, showing it is 'dangerous'.
Ruby
def save!
  # saves data and raises error if it fails
end
Use ? for methods that answer a question about the object.
Ruby
def valid?
  # returns true if data is valid, false otherwise
end
Use ! for methods that modify the object or have important side effects.
Ruby
def update!
  # updates the object and may raise an error
end
Sample Program

This program shows a class with a ? method to check if the name is empty and a ! method to change the name to uppercase.

Ruby
class User
  attr_accessor :name

  def initialize(name)
    @name = name
  end

  def name_empty?
    @name.empty?
  end

  def upcase_name!
    @name.upcase!
  end
end

user = User.new("")
puts user.name_empty?  # true
user.name = "alice"
puts user.name_empty?  # false
user.upcase_name!
puts user.name        # ALICE
OutputSuccess
Important Notes

Not all methods with ! are dangerous, but they usually change the object.

Ruby does not enforce these rules, but following them helps others understand your code.

Use ? only for methods that return true or false.

Summary

Use ? at the end of method names that return true or false.

Use ! at the end of method names that modify the object or are 'dangerous'.

These conventions make your code easier to read and safer to use.