Ruby 定义查找第一个元素或返回nil的方法

Ruby 定义查找第一个元素或返回nil的方法,ruby,Ruby,我想创建一个方法,返回数组的第一个元素,如果它不存在,则返回nil def by_port(port) @collection.select{|x| x.port == port } end 我知道我可以将结果赋给一个变量,如果数组为空,则返回nil,如果不是,则返回first,例如:我认为您在描述问题时遗漏了一些内容-您似乎希望数组中的第一个元素与某个条件匹配,或者如果没有匹配,则返回nil。我之所以有这种印象,是因为使用了带有#select的块 def foo array arr

我想创建一个方法,返回数组的第一个元素,如果它不存在,则返回nil

def by_port(port)
    @collection.select{|x| x.port == port }
end

我知道我可以将结果赋给一个变量,如果数组为空,则返回nil,如果不是,则返回first,例如:

我认为您在描述问题时遗漏了一些内容-您似乎希望数组中的第一个元素与某个条件匹配,或者如果没有匹配,则返回nil。我之所以有这种印象,是因为使用了带有
#select
的块

def foo array
 array.first
end

foo([1]) # => 1
foo([]) # => nil
因此,实际上,您想要的方法已经存在:它是:

detect(ifnone=nil){| obj | block}
→ <代码>obj或
nil

检测(ifnone=nil)
→ <代码>枚举器

enum
中的每个条目传递到
block
。返回第一个
不是
false的块
。如果没有匹配的对象,则调用
ifnone
并在指定时返回其结果,否则返回
nil

下面是一些例子:

因此,在你的情况下:

@collection.detect { |x| x.port == port }
应该有用

@collection.detect { |x| x.port == port }