Home > Enterprise >  Getting Ruby array of indexes which fulfill a certain condition
Getting Ruby array of indexes which fulfill a certain condition

Time:03-12

Problem: I have an array. I am interested in those array elements which fulfil certain conditions. I don't want a new array consisting of those array elements, but an array consisting of the indexes to those elements.

A toy example:

a=[3,4,8,9,11,14]

I want to have an array of the indexes to all the odd elements, i.e. [0, 3, 4].

I came up with the following two solutions, which I both don't like much:

(1)

a.each_index.select {|i| a[i].odd? }

(2)

a.each_with_index.select { |el, i| el.odd? }.map(&:last)

I don't like variant (1), because the repetition of a necessitates that a reasonably should be a variable (and not an arbitrary expression)

I don't like variant (2), because each_with_index constructs an array of small arrays (pairs) consisting of value and index, although I need in the end only the index part.

Basically, I like the approach (2) somewhat better. Does anymody have an idea, how to write it more concisely?

CodePudding user response:

If you are using Ruby version >= 2.7 you can use the filter_map method, like so:

a = [3,4,8,9,11,14]

a.each_with_index.filter_map {|n, i| i if n.odd?}

CodePudding user response:

Input

a = [3, 4, 8, 9, 11, 14]

code

p a.filter_map { |value| a.index(value) if value.odd? }
  •  Tags:  
  • ruby
  • Related