Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
执行&;Ruby中缺少方法_中的块_Ruby_Metaprogramming_Block_Method Missing - Fatal编程技术网

执行&;Ruby中缺少方法_中的块

执行&;Ruby中缺少方法_中的块,ruby,metaprogramming,block,method-missing,Ruby,Metaprogramming,Block,Method Missing,我刚刚开始学习Ruby类中的块和使用method\u missing,我注意到一般公式是 def method_missing(sym, *args, &block) 我的问题是,是否可以在输出中执行&块。例如: class Foo def method_missing(sym, *args, &block) puts "#{sym} was called with #{args} and returned #{block.call(args)}" end e

我刚刚开始学习Ruby类中的块和使用
method\u missing
,我注意到一般公式是

def method_missing(sym, *args, &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} )

有没有一种方法可以使这项工作正常,以便块返回一个新数组?

我想您正在尝试这样做

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

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

我想你是想做这样的事

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

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

我想也许你想要这个:

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

我想也许你想要这个:

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

谢谢,这正是我想要的!这也可以使用收益率来实现吗?是的,可以使用收益率来实现。我用收益率更新答案。谢谢你,这正是我要找的!这也可以使用收益率来实现吗?是的,可以使用收益率来实现。我使用收益率更新答案。谢谢,这实际上也很有帮助。这也可以用
yield
实现吗?谢谢,这实际上也很有帮助。也可以使用
yield
?@CarySwoveland完成此操作,但链接似乎不起作用?这是一篇关于块、进程和lambda之间差异的好文章。(punkinbread:链接现在应该可以了。)@CarySwoveland链接似乎不起作用了?这是一篇关于块、进程和lambda之间差异的好文章。(punkinbread:链接现在应该可以了。)