简体   繁体   English

将传递给方法的块传递给Ruby中的另一个方法

[英]Pass block passed to method to another method in Ruby

I'm trying to write a clone of the ruby keep_if and delete_if array methods. 我正在尝试编写ruby keep_ifdelete_if数组方法的克隆。 Here is my code. 这是我的代码。

module Strain
  def keep
    self.inject([]) do |extracts, element|
      yield(element) ? extracts << element : extracts 
    end
  end

  def discard
    self.inject([]) do |extracts, element|
      !yield(element) ? extracts << element : extracts
    end
  end
end

class Array
  include Strain
end

This works. 这有效。 But I want to do something like: 但我想做的事情如下:

def discard
  self - self.keep &block
end

Desired behaviour: 期望的行为:

[1, 2, 3].discard { |number| number < 2 }
# => [2, 3]

So I need to pass the block that is passed to the discard method, to be passed on to the keep method. 所以我需要传递传递给discard方法的块,然后传递给keep方法。 How do I achieve this? 我该如何实现这一目标?

You can reference the block explicitly 您可以显式引用该块

def discard(&block)
  self - self.keep(&block)
end

or implicitly 或含蓄地

def discard
  self - self.keep(&Proc.new {})
end

In your case, I would suggest the first approach. 在你的情况下,我会建议第一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM