2016-01-24 14 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 } 

應該工作。

相關問題