Ruby: how to find the next match in an array

I need to search for an element in an array and return the value of the next element. Example:

a = ['abc.df','-f','test.h']
i = a.find_index{|x| x=~/-f/}
puts a[i+1]

Is there a better way besides working with the index?

0
source share
4 answers

The classic functional approach does not use indices ( xs.each_cons(2)→ pairwise combinations of xs):

xs = ['abc.df', '-f', 'test.h']
(xs.each_cons(2).detect { |x, y| x =~ /-f/ } || []).last
#=> "test.h"

Using Enumerated # map_detect simplifies it more:

xs.each_cons(2).map_detect { |x, y| y if x =~ /-f/ }
#=> "test.h"
+3
source

The reason for something of the type is array.find{something}.nextnot that it is an array, not a linked list. Each element is its own value; he has no concept of an element after me.

@tokland , , , , . , . , , , .

, , - , , , singleton a:

def a.find_after(&test)
  self[find_index(&test).next]
end

a.find_after{|x| x=~/-f/}

- .

, , @BenjaminCox , . , , .

+3

. , , . , OptionParser - , .

, .

+1

, , , . Enumerable#drop_while, :

a = ['abc.df','-f','test.h']
f_arg = a.drop_while { |e| e !~ /-f/ }[1]
0

Source: https://habr.com/ru/post/1617979/


All Articles