我刚刚开始学习块并在Ruby课程中使用method_missing
,我已经注意到了通用公式
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 :(得分: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?}"
答案 1 :(得分:0)
我认为你正试图做这样的事情?
def foo(*args, &block)
args.map(&block)
end
foo(1, 2, 3) { |n| n + 2 } #=> [3, 4, 5]