0
0
Rubyprogramming~3 mins

Why Method naming conventions (? and ! suffixes) in Ruby? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your method names could warn you about surprises before you even run the code?

The Scenario

Imagine you have many methods in your Ruby program, but none of them clearly tell you if they just check something or if they change data. You have to guess or read the code every time.

The Problem

This guessing wastes time and causes mistakes. You might call a method thinking it only checks a value, but it actually changes it! This can break your program in ways that are hard to find.

The Solution

Ruby uses special method name endings: ? for methods that answer yes/no questions without changing anything, and ! for methods that do something risky or change data. This helps you understand what methods do just by their names.

Before vs After
Before
def save
  # saves data
end

def save?
  # unclear if it checks or saves
end
After
def save!
  # saves data and might raise error
end

def saved?
  # clearly checks if saved
end
What It Enables

This naming style lets you quickly know if a method is safe to call or if it might change things, making your code easier and safer to use.

Real Life Example

When you call user.valid?, you know it just checks if the user data is good. But user.save! will try to save and might raise an error if something goes wrong. This saves you from surprises.

Key Takeaways

Method names ending with ? mean they check and return true/false without changing anything.

Method names ending with ! mean they do something important or risky, like changing data or raising errors.

This helps you write and read code that is clear and less error-prone.