2013-12-11 19 views
1

我刚开始学习块和Ruby类使用method_missing,而且我发现通式为执行的与块的method_missing在Ruby中

def method_missing(sym, *args, &block) 

我的问题是,如果有可能执行输出中为&block。例如:

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}) 

有没有办法让这个工作,使块返回一个新的数组?

+0

@CarySwoveland链接似乎不工作? – reichertjalex

+0

[这里](http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/)是一个很好的文章,关于块,procs和lambdas之间的差异。 (punkinbread:链接应该现在就OK。) –

回答

1

我想,也许你想这样的:

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 

执行结果:

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

更新时间:收益率,可以使用如下。

puts "#{sym} was called with #{args} and returned #{yield(args) if block_given?}" 
+0

谢谢,这正是我一直在寻找的!这也可以用'yield'完成吗? – reichertjalex

+1

是的,它可以使用良率完成。我使用收益更新答案。 – uncutstone

0

我想你正在尝试做这样的事情?

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

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

谢谢,这实际上也有很大的帮助。这也可以用'yield'完成吗? – reichertjalex

相关问题