Concept Flow - Method naming conventions (? and ! suffixes)
Define method
Check method name suffix
Returns boolean
Use in condition
End method call
Ruby methods ending with ? return true/false; methods ending with ! modify data or are 'dangerous'.
def empty? self.size == 0 end def upcase! # modifies string in place end
| Step | Method Called | Suffix | Behavior | Output/Effect |
|---|---|---|---|---|
| 1 | empty? | ? | Returns boolean | true or false depending on condition |
| 2 | upcase! | ! | Modifies object in place | String changed, returns modified string |
| 3 | empty? | ? | Returns boolean | false if not empty |
| 4 | upcase! | ! | Modifies object in place | String changed again |
| 5 | Call ends | - | - | Program continues |
| Variable | Start | After empty? call | After upcase! call | After second upcase! call | Final |
|---|---|---|---|---|---|
| string | "hello" | "hello" | "HELLO" | "HELLO" | "HELLO" |
| empty_check | nil | false | false | false | false |
Ruby method names ending with ? return true/false (boolean checks). Methods ending with ! usually modify the object or perform 'dangerous' actions. ? methods are safe queries; ! methods warn to use with caution. Use ? for predicates, ! for mutating or risky methods. This naming helps understand method behavior at a glance.
? is used at the end of method names that return true or false.? suffix? return true or false, indicating a boolean check.valid? clearly suggests a boolean check, while others do not.! suffix! usually modify the object or perform a 'dangerous' action.delete! clearly indicates modification, while delete may not, and delete? suggests a boolean check.class User
def active?
true
end
def deactivate!
@active = false
"User deactivated"
end
end
user = User.new
puts user.active?
puts user.deactivate!
puts user.active?active? methodtrue because it returns the literal true without checking any variable.deactivate! method and second active? calldeactivate! sets @active = false but active? does not use @active, so it still returns true.def save? # saves the object puts "Saving..." true end
? suffix? should return true or false and not perform side effects like saving.?.?, e.g., empty?.!, e.g., clear!.Pass the test and this pattern moves unknown