What is the output of this Ruby code?
class Greeter def hello "Hello, world!" end end g = Greeter.new m = g.method(:hello) puts m.call
Remember that method(:name) returns a method object that you can call.
The method(:hello) returns a method object bound to g. Calling m.call runs hello and returns "Hello, world!".
Which statement about Ruby method objects created by method() is true?
Think about what happens when you call method(:name) on an object.
Method objects are bound to the specific object they come from, so they keep that object's state when called.
What error does this Ruby code produce?
class Person def greet "Hi!" end end m = Person.instance_method(:greet) m.call
Consider what instance_method returns and how it differs from method.
instance_method returns an unbound method that must be bound to an object before calling. Calling m.call without binding raises an ArgumentError because no receiver is given.
Which option correctly converts a method object to a proc and calls it?
class Calculator def double(x) x * 2 end end calc = Calculator.new m = calc.method(:double) # call the method object as a proc with argument 5
Check the correct method name to convert a method object to a proc and how to call it with arguments.
to_proc converts the method object to a proc. Then you can call it with arguments like p.call(5).
You want to store multiple method objects from different instances and call them later. Which code snippet correctly stores and calls these method objects?
class Worker def initialize(name) @name = name end def work "#{@name} is working" end end w1 = Worker.new("Alice") w2 = Worker.new("Bob") callbacks = [] # store method objects from w1 and w2 callbacks << w1.method(:work) callbacks << w2.method(:work) # call all stored callbacks and collect results results = callbacks.map { |m| m.call } puts results
Think about how method objects keep their binding to the original instance.
Each method object remembers the instance it came from, so calling them later returns the correct string with the instance's name.