我如何修改我的 ruby 方法,以便它也接受一个代码块



我有一个名为myFilter的方法,它接收一个数组,并过滤掉不符合要求的元素。

例如。

arr = [4,5,8,9,1,3,6]
answer = myfilter(arr) {|i| i>=5}

此运行将返回一个包含元素 5,8,9,6 的数组,因为它们都大于或等于 5。

我将如何实现它? 算法很简单,但我不明白我们如何接受这种情况。

谢谢。

我认为您不想使用select方法或类似方法,但您想了解块的工作原理。

def my_filter(arr)
  if block_given?
    result = []
    arr.each { |element| result.push(element) if yield element } # here you use the block passed to this method and execute it with the current element using yield
    result
  else
    arr
  end
end

惯用的方式是:

def my_filter(arr)
  return enum_for(:my_filter, arr) unless block_given?
  arr.each_with_object([]) do |e, acc|
    acc << e if yield e
  end
end

更多信息Enumerator::Lazy#enum_for .

你可以做

def my_filter(arr, &block)
  arr.select(&block)
end

然后打电话

my_filter([1, 2, 3]) { |e| e > 2 }
=> [3]

但相反,您可以直接使用块调用select:)

最新更新