在Ruby中访问传递的块 [英] Accessing a passed block in Ruby

查看:80
本文介绍了在Ruby中访问传递的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接受一个块的方法,让我们将其称为外部.反过来,它调用接受另一个块的方法,将其称为内部.

I have a method that accepts a block, lets call it outer. It in turn calls a method that accepts another block, call it inner.

我想发生的事情是让外部调用内部,将其传递给一个新块,该新块调用第一个块.

What I would like to have happen is for outer to call inner, passing it a new block which calls the first block.

这是一个具体的例子:

class Array
  def delete_if_index
    self.each_with_index { |element, i| ** A function that removes the element from the array if the block passed to delete_if_index is true }
  end
end

['a','b','c','d'].delete_if_index { |i| i.even? }
  => ['b','d']

传递给delete_if_index的块由传递给each_with_index的块调用.

the block passed to delete_if_index is called by the block passed to each_with_index.

在Ruby中是否有可能,更广泛地讲,我们对接收它的函数中的块有多少访问权限?

Is this possible in Ruby, and, more broadly, how much access do we have to the block within the function that receives it?

推荐答案

您可以将一个块包装在另一个块中:

You can wrap a block in another block:

def outer(&block)
  if some_condition_is_true
    wrapper = lambda {
      p 'Do something crazy in this wrapper'
      block.call # original block
    }
    inner(&wrapper)
  else
    inner(&passed_block)
  end
end

def inner(&block)
  p 'inner called'
  yield
end

outer do
  p 'inside block'
  sleep 1
end

我会说打开一个现有的块并更改其内容是做错了 TM ",也许继续传递会有所帮助吗?我也要警惕绕过有副作用的障碍.我尝试保持lambda的确定性,并采取诸如删除方法主体中的内容之类的操作.在复杂的应用程序中,这可能会使调试变得容易得多.

I'd say opening up an existing block and changing its contents is Doing it WrongTM, maybe continuation-passing would help here? I'd also be wary of passing around blocks with side-effects; I try and keep lambdas deterministic and have actions like deleting stuff in the method body. In a complex application this will likely make debugging a lot easier.

这篇关于在Ruby中访问传递的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆