Bird
0
0

Given this code, how can you store multiple method objects from an object obj for methods :foo and :bar and call them later?

hard📝 Application Q8 of 15
Ruby - Blocks, Procs, and Lambdas
Given this code, how can you store multiple method objects from an object obj for methods :foo and :bar and call them later?
class Example
  def foo
    "foo called"
  end
  def bar
    "bar called"
  end
end

obj = Example.new
Amethods = [obj.method(:foo), obj.method(:bar)]; methods.each { |m| puts m.call }
Bmethods = obj.methods(:foo, :bar); methods.call
Cmethods = obj.method(:foo, :bar); methods.call
Dmethods = [obj.foo, obj.bar]; methods.call
Step-by-Step Solution
Solution:
  1. Step 1: Obtain Method objects individually

    Use obj.method(:foo) and obj.method(:bar) to get Method objects.
  2. Step 2: Store in an array and call each

    Store them in an array and iterate to call each method object.
  3. Final Answer:

    methods = [obj.method(:foo), obj.method(:bar)]; methods.each { |m| puts m.call } -> Option A
  4. Quick Check:

    Store multiple Method objects in array and call each [OK]
Quick Trick: Store Method objects in array, call each with .call [OK]
Common Mistakes:
  • Trying to get multiple methods in one method() call
  • Calling methods array directly without iteration
  • Storing method results instead of Method objects

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes