Bird
0
0

What will happen if you try to get a Method object for a non-existent method :run on an object dog in Ruby?

medium📝 Debug Q6 of 15
Ruby - Blocks, Procs, and Lambdas
What will happen if you try to get a Method object for a non-existent method :run on an object dog in Ruby?
class Dog
  def bark
    "Woof!"
  end
end

d = Dog.new
m = d.method(:run)
m.call
AIt returns nil since the method is missing
BIt raises a NameError because the method :run does not exist
CIt returns a Method object that calls method_missing
DIt calls the method :run directly without error
Step-by-Step Solution
Solution:
  1. Step 1: Understand method lookup

    Ruby's method(:name) looks for an existing method with the given symbol.
  2. Step 2: Check if method exists

    Since :run is not defined in Dog, Ruby raises an error.
  3. Final Answer:

    It raises a NameError because the method :run does not exist -> Option B
  4. Quick Check:

    Calling method with an undefined method name raises NameError [OK]
Quick Trick: method(:name) fails if method doesn't exist [OK]
Common Mistakes:
  • Assuming method returns nil for missing methods
  • Thinking method calls method_missing automatically
  • Expecting method to call the method directly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes