1

我刚刚开始学习块并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} )

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

4

2 回答 2

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?}"
于 2013-12-11T03:09:13.867 回答
0

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

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

foo(1, 2, 3) { |n| n + 2 } #=> [3, 4, 5]
于 2013-12-11T02:34:58.270 回答