如何从数组中提取匹配条件的第一个元素?

时间:2014-03-18 09:58:13

标签: ruby arrays

我正在尝试提取符合条件的数组的第一个元素。

想象一下,我有这个数组:

a = [1,2,3,4,5,6,7]

如何提取大于4的第一个元素,获取数组[1,2,3,4,6,7]和提取的元素5

6 个答案:

答案 0 :(得分:5)

ar = [1,2,3,4,5,6,7]
found = ar.delete_at(ar.index{|el| el>4})
p found # => 5
p ar    # => [1, 2, 3, 4, 6, 7]

答案 1 :(得分:1)

不确定为什么没有人提到完全符合您要求的find方法。

a = [1,2,3,4,5,6,7]
b = a.delete(a.find{|n| n > 4}) 
#=> 5
a
#=> [1,2,3,4,6,7]

或非破坏性(现在原始数组仍然存在于original_a中,b是符合条件的第一个元素,a现在是修改后的Array)< / p>

a = [1,2,3,4,5,6,7]
original_a,b = a.dup, a.delete(a.find{|e| e > 4})
original_a
#=> [1,2,3,4,5,6,7]
b
#=> 5
a 
#=>[1,2,3,4,6,7] 

答案 2 :(得分:0)

只做

a = [1,2,3,4,5,6,7]
ind = a.index { |i| i > 4 }
rest_indices = [*0...a.size] - [ind]
first,ary = a[ind],a.values_at(*rest_indices)

答案 3 :(得分:0)

您可以使用Enumerable#find然后删除找到的元素:

index = a.index { |i| i > 4 }
first_element = a[index]
a.delete_at index

答案 4 :(得分:0)

试试这个:

ar = [1,2,3,4,5,6,7]

方法1:

ar - [ele = ar.select{|a| a > 4 }.first]
#=> [1, 2, 3, 4, 6, 7]

ele
#=> 5

ar
#=> [1,2,3,4,5,6,7]

方法2:

ar_selected = ar.select{|a| a > 4 }
ar_pruned, first_matched_ele = ar - [ar_selected.first], ar_selected.first
#=> [[1, 2, 3, 4, 6, 7], 5]

first_matched_ele
#=> 5

ar_pruned
#=> [1, 2, 3, 4, 6, 7]

ar
#=> [1,2,3,4,5,6,7]

答案 5 :(得分:0)

另一种方法,使用Enumerable#partition

found = false
elem, arr = a.partition { |x| (!found) && (found||= x>4) }
# => [[5], [1, 2, 3, 4, 6]] 
elem
#=> [5]
arr
#=> [1, 2, 3, 4, 6]