0
0
Rubyprogramming~20 mins

Method objects with method() in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Method Object Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of calling a method object

What is the output of this Ruby code?

Ruby
class Greeter
  def hello
    "Hello, world!"
  end
end

g = Greeter.new
m = g.method(:hello)
puts m.call
AHello, world!
BNoMethodError
Cnil
DArgumentError
Attempts:
2 left
💡 Hint

Remember that method(:name) returns a method object that you can call.

🧠 Conceptual
intermediate
2:00remaining
Understanding method objects and binding

Which statement about Ruby method objects created by method() is true?

AThey automatically convert to procs when assigned to variables.
BThey cannot be called more than once.
CThey are bound to the object they were created from and remember its state.
DThey are unbound and can be called on any object of the same class.
Attempts:
2 left
💡 Hint

Think about what happens when you call method(:name) on an object.

🔧 Debug
advanced
2:00remaining
Identify the error when calling an unbound method

What error does this Ruby code produce?

Ruby
class Person
  def greet
    "Hi!"
  end
end

m = Person.instance_method(:greet)
m.call
AArgumentError
BTypeError
CNameError
DUnboundMethodError
Attempts:
2 left
💡 Hint

Consider what instance_method returns and how it differs from method.

📝 Syntax
advanced
2:00remaining
Correct way to convert a method object to a proc

Which option correctly converts a method object to a proc and calls it?

Ruby
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
Ap = m.to_proc(5); puts p.call
Bp = m.proc; puts p.call(5)
Cp = m.to_proc; puts p.call
Dp = m.to_proc; puts p.call(5)
Attempts:
2 left
💡 Hint

Check the correct method name to convert a method object to a proc and how to call it with arguments.

🚀 Application
expert
3:00remaining
Using method objects to implement a callback system

You want to store multiple method objects from different instances and call them later. Which code snippet correctly stores and calls these method objects?

Ruby
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
A["is working", "is working"]
B["Alice is working", "Bob is working"]
C["Alice", "Bob"]
DRuntimeError
Attempts:
2 left
💡 Hint

Think about how method objects keep their binding to the original instance.