0
0
Rubyprogramming~20 mins

Method naming conventions (? and ! suffixes) in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Method Naming Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Ruby code with a method ending with '?'?
Consider the following Ruby code. What will be printed when calling even_number??
Ruby
def even_number?(num)
  num % 2 == 0
end

puts even_number?(4)
puts even_number?(5)
Anil\nnil
Bfalse\ntrue
C4\n5
Dtrue\nfalse
Attempts:
2 left
💡 Hint
Methods ending with '?' usually return true or false.
Predict Output
intermediate
2:00remaining
What does the method ending with '!' do differently?
Look at this Ruby code. What will be the output after calling capitalize! on the string?
Ruby
str = "hello"
result = str.capitalize!
puts str
puts result
Ahello\nHello
BHello\nHello
CHello\nhello
Dhello\nhello
Attempts:
2 left
💡 Hint
Methods ending with '!' usually modify the object itself.
🔧 Debug
advanced
2:00remaining
Why does this method with '?' suffix raise an error?
This Ruby method is intended to check if a number is positive. Why does it raise a syntax error?
Ruby
def positive?(num)
  if num > 0
    return true
  else
    return false
  end
end
ABecause the 'end' keyword is followed by an extra '?', which is invalid syntax.
BBecause method names cannot end with '?' and have an extra '?' after 'end'.
CBecause 'return' cannot be used inside methods ending with '?'.
DBecause the method is missing a closing parenthesis.
Attempts:
2 left
💡 Hint
Check the syntax after the method body ends.
Predict Output
advanced
2:00remaining
What is the output of this code using both '?' and '!' methods?
Given this Ruby code, what will be printed?
Ruby
class User
  attr_accessor :name

  def initialize(name)
    @name = name
  end

  def name?
    !@name.nil? && !@name.empty?
  end

  def clear_name!
    @name = ""
  end
end

user = User.new("Alice")
puts user.name?
user.clear_name!
puts user.name?
Atrue\ntrue
Bfalse\ntrue
Ctrue\nfalse
Dfalse\nfalse
Attempts:
2 left
💡 Hint
The '?' method checks if name is present; the '!' method clears it.
🧠 Conceptual
expert
2:00remaining
Why should methods ending with '!' be used carefully in Ruby?
Which of the following best explains the purpose and caution behind methods ending with '!' in Ruby?
AThey indicate methods that modify the object in place and may have side effects, so use them only when you want to change the original object.
BThey are methods that always return true or false and should be used for checks only.
CThey are methods that raise exceptions on failure and never modify the object.
DThey are deprecated methods and should be avoided in modern Ruby code.
Attempts:
2 left
💡 Hint
Think about what the '!' means in method names in Ruby conventions.