![](/img/trans.png)
[英]Ruby/Rails: get elements from array where indices are divisible by x
[英]Ruby: How to get the indices of the first x array elements that match a condition?
我有兩個句子,一個是德語,另一個是英語。 我將在德語句子中搜索包含某個單詞的句子,如果存在,我將檢查是否存在等效的英語句子(使用帶有連接信息的哈希)。 但是,如果用戶正在尋找一個非常普通的單詞,我不想返回包含該單詞的每個句子,而只返回第一個x匹配項,然后停止搜索。
如果我這樣做german_sentences.index { |sentence| sentence.include?(word) }
german_sentences.index { |sentence| sentence.include?(word) }
我得到在同一時間只有一個匹配。 如果我使用german_sentences.keep_if { |sentence| sentence.include?(word) }
german_sentences.keep_if { |sentence| sentence.include?(word) }
我得到的所有比賽,也失去了索引信息,這是本真正的關鍵。
我現在使用一個自定義循環與each_with_index並在達到最大值后中斷,但是我真的覺得我必須缺少一些現有的解決方案,至少是某些提供有限匹配項(即使不是其索引)的解決方案。 。
german_sentences
.each_index
.lazy
.select{|i| german_sentences[i].include?(word)}
.first(n)
如果您的需求不是一次性的,則可以使用Module#refine ,而不是monkeypatching Array
)。 在實驗中, refine
已添加到v2.0,然后在2.1版中進行了很大的更改。 使用優化的限制之一是: “您只能在頂層激活優化...” ,這顯然會阻止在Pry和IRB中進行測試。
module M
refine Array do
def select_indices_first(n)
i = 0
k = 0
a = []
return a if n == 0
each { |x| (a << i; k += 1) if yield(x); break if k == n; i += 1 }
a
end
def select_first(n) # if you wanted this also...
k = 0
a = []
return a if n == 0
each { |x| (a << x; k += 1) if yield(x); break if k == n }
a
end
end
end
using M
sentences = ["How now brown", "Cat", "How to guide", "How to shop"]
sentences.select_indices_first(0) {|s| s.include?("How")} # => []
sentences.select_indices_first(1) {|s| s.include?("How")} # => [0]
sentences.select_indices_first(2) {|s| s.include?("How")} # => [0, 2]
sentences.select_indices_first(3) {|s| s.include?("How")} # => [0, 2, 3]
sentences.select_indices_first(99) {|s| s.include?("How")} # => [0, 2, 3]
sentences.select_first(2) {|s| s.include?("How")}
# => ["How now brown", "How to guide"]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.