簡體   English   中英

如何檢查數組的數組在內部數組中是否有值?

[英]How do I check to see if an array of arrays has a value within the inner arrays?

假設我有一個數組,看起來像這樣:

[[1830, 1], [1859, 1]]

我想做的是快速掃描內部數組,看是否其中任何一個包含數字1830 如果是這樣,我希望它返回整個數組,該數組包含上例中的數字1830 ,又名[1830, 1]

我知道對於一個普通的值數組,我只會做array.include? 1830 array.include? 1830 ,但這在這里不起作用,如下所示:

@add_lines_num_start
#=> [[1830, 1], [1859, 1]]
@add_lines_num_start.include? 1830
#=> false
@add_lines_num_start.first.include? 1830
#=> true

我怎么做?

a = [[1830, 1], [1859, 1]]
a.find { |ar| ar.grep(1830) }
#=> [1830, 1]

參考文獻:

編輯1

正如@Ilya在評論中提到的,而不是使用grep遍歷整個數組,您可以使用方法返回找到符合條件的布爾值:

a.find { |ar| ar.include?(1830) }

參考文獻:

編輯2(在OP下@Cary的評論中無恥地被盜)

萬一數組中有多個匹配數組,可以使用Enumerable# find_all

a = [[1830, 1], [1859, 1], [1893, 1830]]
a.find_all { |ar| ar.include?(1830) }
#=> [[1830, 1], [1893, 1830]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM