Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q5 of 15
Ruby - Classes and Objects
What will be the output of this Ruby code?
class Score
  def initialize(points)
    @points = points
  end
  def to_s
    "Points: #{@points}"
  end
end

score = Score.new(42)
puts score.to_s
A42
Bscore
C#<Score:0x00007fffe0a1b8>
DPoints: 42
Step-by-Step Solution
Solution:
  1. Step 1: Understand the to_s method

    The to_s method returns the string "Points: " concatenated with the value of @points.
  2. Step 2: Check the output of puts

    puts score.to_s prints the returned string from to_s.
  3. Final Answer:

    Points: 42 -> Option D
  4. Quick Check:

    Output matches the string returned by to_s [OK]
Quick Trick: to_s returns string, puts prints it [OK]
Common Mistakes:
  • Expecting object default inspect output
  • Confusing puts with return value

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes