Executing the &block in method_missing in Ruby

648 views Asked by At

I've just began learning about blocks and using method_missing in Ruby classes, and I've noticed the general formula is

def method_missing(sym, *args, &block)

My question is if it's possible to execute the &block in the output. For example:

class Foo
  def method_missing(sym, *args, &block)
     puts "#{sym} was called with #{args} and returned #{block.call(args)}"
  end
end

bar = Foo.new
bar.test(1,2,3, lambda {|n| n + 2} )

Is there a way to make this work so that the block returns a new array?

2

There are 2 answers

2
uncutstone On BEST ANSWER

I think maybe you want this:

class Foo
  def method_missing(sym, *args, &block)
     puts "#{sym} was called with #{args} and returned #{block.call(args)}"
  end
end

bar = Foo.new
bar.test(1,2,3) do |a| 
  a.map{|e| e + 2}
end

Execution result:

test was called with [1, 2, 3] and returned [3, 4, 5]

Updated: yield can be used as below.

 puts "#{sym} was called with #{args} and returned #{yield(args) if block_given?}"
1
Kaleidoscope On

I think you're trying to do something like this?

def foo(*args, &block)
  args.map(&block)
end

foo(1, 2, 3) { |n| n + 2 } #=> [3, 4, 5]