2016-01-24 106 views
-3

我想创建一个返回数组的第一个元素的方法,或者在它不存在的情况下为nil。定义一个方法找到第一个元素或返回nil

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

我知道我可以把结果赋值给一个变量,如果数组为空或第一如果没有,像返回nil:

回答

4
def foo array 
array.first 
end 

foo([1]) # => 1 
foo([]) # => nil 
5

我想你已经错过了一些东西在你的描述问题 - 您似乎希望数组的第一个元素匹配某个条件nil(如果没有)。由于使用#select的块,我得到了这种印象。

所以,实际上,你想要的已经存在的方法:这是Array#detect

detect(ifnone = nil) { |obj| block }objnil

detect(ifnone = nil)an_enumerator

通行证在enumblock每个条目。返回block不是false的第一个。如果没有对象匹配,则调用ifnone,并在指定时返回结果,否则返回nil

而且它的例子:

(1..10).detect { |i| i % 5 == 0 and i % 7 == 0 } #=> nil 
(1..100).find { |i| i % 5 == 0 and i % 7 == 0 } #=> 35 

所以,你的情况:

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

应该工作。

相关问题