简体   繁体   English

如何在Ruby中创建可重用的块/ proc / lambda?

[英]How do I create a reusable block/proc/lambda in Ruby?

I want to create a filter, and be able to apply it to an array or hash. 我想创建一个过滤器,并能够将其应用于数组或散列。 For example: 例如:

def isodd(i)
  i % 2 == 1
end

The I want to be able to use it like so: 我希望能够像这样使用它:

x = [1,2,3,4]
puts x.select(isodd)
x.delete_if(isodd)
puts x

This seems like it should be straight forward, but I can't figure out what I need to do it get it to work. 这似乎应该是直截了当的,但我无法弄清楚我需要做什么才能让它发挥作用。

Create a lambda and then convert to a block with the & operator: 创建一个lambda,然后使用&运算符转换为块:

isodd = lambda { |i| i % 2 == 1 }
[1,2,3,4].select(&isodd)
puts x.select(&method(:isodd))

You can create a named Proc and pass it to the methods that take blocks: 您可以创建一个名为Proc并将其传递给采用块的方法:

isodd = Proc.new { |i| i % 2 == 1 }
x = [1,2,3,4]
x.select(&isodd) # returns [1,3]

The & operator converts between a Proc / lambda and a block, which is what methods like select expect. &运算符在Proc / lambda和块之间进行转换,这就像select expect这样的方法。

If you are using this in an instance, and you do not require any other variables outside of the scope of the proc (other variables in the method you're using the proc in), you can make this a frozen constant like so: 如果你在一个实例中使用它,并且你不需要在proc范围之外的任何其他变量(你正在使用proc的方法中的其他变量),你可以使它成为一个冻结常量,如下所示:

ISODD = -> (i) { i % 2 == 1 }.freeze
x = [1,2,3,4]
x.select(&ISODD)

Creating a proc in Ruby is a heavy operation (even with the latest improvements), and doing this helps mitigate that in some cases. 在Ruby中创建一个proc是一项繁重的操作(即使有最新的改进),这样做有助于在某些情况下缓解这种情况。

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

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