我想創建一個返回數組的第一個元素的方法,或者在它不存在的情況下爲nil。定義一個方法找到第一個元素或返回nil
def by_port(port)
@collection.select{|x| x.port == port }
end
我知道我可以把結果賦值給一個變量,如果數組爲空或第一如果沒有,像返回nil:
我想創建一個返回數組的第一個元素的方法,或者在它不存在的情況下爲nil。定義一個方法找到第一個元素或返回nil
def by_port(port)
@collection.select{|x| x.port == port }
end
我知道我可以把結果賦值給一個變量,如果數組爲空或第一如果沒有,像返回nil:
def foo array
array.first
end
foo([1]) # => 1
foo([]) # => nil
我想你已經錯過了一些東西在你的描述問題 - 您似乎希望數組的第一個元素匹配某個條件或nil
(如果沒有)。由於使用#select
的塊,我得到了這種印象。
所以,實際上,你想要的已經存在的方法:這是Array#detect
:
detect(ifnone = nil) { |obj| block }
→obj
或nil
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 }
應該工作。