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

时间:2016-01-24 02:36:20

标签: ruby

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

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

我知道我可以将结果分配给变量,如果数组为空则返回nil,否则返回nil,如:

2 个答案:

答案 0 :(得分:5)

我认为您在问题描述中遗漏了一些内容 - 您似乎希望数组的第一个元素符合某个条件,或者nil如果没有确实。由于使用了#select的块,我得到了这种印象。

所以,实际上,您想要的方法已经存在:它Array#detect

  

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

     

detect(ifnone = nil)an_enumerator

     

enum中的每个条目传递给block。返回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 }

应该有用。

答案 1 :(得分:4)

def foo array
 array.first
end

foo([1]) # => 1
foo([]) # => nil
相关问题