mike927 mike927 - 3 months ago 23
Ruby Question

Ruby - Block scope inside method

I created some class

class Book
def perform
yield
end
end


Then I want to call the block which will call
method1
and
method2
. However both methods are defined nowhere and I dont want to define them. Instead of this I'd like to call method_missing but I get:
undefined local variable or method 'method1' for main:Object (NameError)


book = Book.new
book.perform do
method1
method2
end


What Should I do then?

Answer

In order to do what you ask I believe you need to redefine method_missing like so:

class Book
  def perform
    yield
  end
end

def method_missing(methodname, *args)
  puts "#{methodname} called"
end

book = Book.new
book.perform do
  method1
  method2
end

#=>
#method1 called
#method2 called