Consider this Ruby class that uses method_missing and respond_to_missing?. What will be printed when calling obj.greet?
class Greeter def respond_to_missing?(method_name, include_private = false) method_name == :greet || super end def method_missing(method_name, *args, &block) if method_name == :greet "Hello!" else super end end end obj = Greeter.new puts obj.greet
Check how respond_to_missing? affects method detection and how method_missing handles calls.
The respond_to_missing? method tells Ruby that the object responds to :greet. When obj.greet is called, method_missing catches it and returns "Hello!".
Why is it important to implement respond_to_missing? when you override method_missing in Ruby?
Think about how Ruby checks if an object responds to a method before calling it.
Implementing respond_to_missing? ensures that methods like respond_to? and others that check method availability work correctly with dynamic methods handled by method_missing.
Examine this Ruby code snippet. What error will it raise when calling obj.foo and why?
class Speaker < BasicObject def respond_to_missing?(method_name, include_private = false) method_name == :hello end def method_missing(method_name, *args, &block) if method_name == :hello "Hi!" else super end end end obj = Speaker.new puts obj.foo
Check what happens when super is called inside method_missing without a parent method_missing.
The super call in method_missing tries to call the parent's method_missing, but BasicObject does not define it, causing a NoMethodError.
Which of the following Ruby code snippets correctly implements respond_to_missing? to handle dynamic methods starting with 'find_'?
Remember the method signature and that method_name is a symbol.
Option B correctly converts method_name to string and checks if it starts with 'find_'. It also calls super for other cases. Option B misses the second argument and calls start_with? on a symbol, causing error. Option B misses super call. Option B uses include? instead of start_with?, which is not the requirement.
Given this Ruby class, how many methods will obj.respond_to? return true for, when checking :foo1, :foo2, :bar, and :baz?
class DynamicResponder def respond_to_missing?(method_name, include_private = false) method_name.to_s.start_with?("foo") || super end def method_missing(method_name, *args, &block) if method_name.to_s.start_with?("foo") "Handled #{method_name}" else super end end end obj = DynamicResponder.new results = { foo1: obj.respond_to?(:foo1), foo2: obj.respond_to?(:foo2), bar: obj.respond_to?(:bar), baz: obj.respond_to?(:baz) } puts results.select { |_, v| v }.size
Check which method names start with 'foo' and how respond_to_missing? works.
The object responds to methods starting with 'foo' only. So :foo1 and :foo2 return true, but :bar and :baz return false. Hence, 2 methods respond true.