Bird
0
0

What will be the output of this Ruby code?

hard📝 Application Q8 of 15
Ruby - Classes and Objects
What will be the output of this Ruby code?
class Demo
  def self.execute
    new.instance_action
  end
  def instance_action
    self.class.name
  end
end
puts Demo.execute
A"Demo"
B"Demo.execute"
C"Demo::instance_action"
DAn error is raised
Step-by-Step Solution
Solution:
  1. Step 1: Understand self in instance method

    Inside instance_action, self refers to the instance of Demo.
  2. Step 2: Calling self.class.name

    self.class returns the class of the instance, which is Demo. Calling .name returns the string "Demo".
  3. Step 3: Execution flow

    Demo.execute calls new.instance_action, so the output is "Demo".
  4. Final Answer:

    "Demo" -> Option A
  5. Quick Check:

    self.class.name returns class name string [OK]
Quick Trick: self.class.name returns the class name string [OK]
Common Mistakes:
  • Assuming self.class returns a method or instance
  • Expecting the method name instead of class name
  • Thinking it raises an error due to new instance creation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes