Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q4 of 15
Ruby - Methods
What will be the output of this Ruby code?
class Light
  def on?
    true
  end

  def on!
    puts "Turning on"
  end
end

light = Light.new
puts light.on?
light.on!
Atrue\nTurning on
BTurning on\ntrue
Ctrue\ntrue
DTurning on\nTurning on
Step-by-Step Solution
Solution:
  1. Step 1: Analyze method on?

    This method returns true, so puts light.on? prints "true".
  2. Step 2: Analyze method on!

    This method prints "Turning on" using puts, so calling light.on! outputs "Turning on".
  3. Final Answer:

    true\nTurning on -> Option A
  4. Quick Check:

    ? = boolean return, ! = modifies or side effect [OK]
Quick Trick: ? returns boolean, ! often has side effects [OK]
Common Mistakes:
  • Mixing output order
  • Assuming on? prints instead of returns
  • Confusing puts output with return value

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes