Frage

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?

War es hilfreich?

Lösung

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?}"

Andere Tipps

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]
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top