Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Classes and Objects
What will be the output of this Ruby code?
class Person
  def initialize(name)
    @name = name
  end
  def greet
    "Hello, #{@name}!"
  end
end

p = Person.new("Alice")
puts p.greet
AHello, @name!
BHello, Alice!
CHello, !
DError: undefined method greet
Step-by-Step Solution
Solution:
  1. Step 1: Understand object creation and initialization

    The Person.new("Alice") calls initialize with "Alice", setting @name to "Alice".
  2. Step 2: Check the greet method output

    The greet method returns "Hello, #{@name}!" which becomes "Hello, Alice!" when printed.
  3. Final Answer:

    Hello, Alice! -> Option B
  4. Quick Check:

    Instance variable set in initialize used in greet [OK]
Quick Trick: Instance variables set in initialize are accessible in other methods [OK]
Common Mistakes:
  • Expecting '@name' to print literally
  • Forgetting to call greet method
  • Confusing instance variable scope

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes