Ruby: 1.8.7: How to find indexes in an array where elements are not zero?

my_array = [0, 1, 2, nil, nil, 3, nil, 4, nil]

must return [0,1,2,5,7]

via @the tin man: state.map.with_index {| e i | (e.nil?)? nil: i} .compact

unfortunately this only works with 1.9

+3
source share
2 answers

This happens with v1.9.2:

my_array.map.with_index{ |e,i| (e.nil?) ? i : nil }.compact
 => [3, 4, 6, 8] 

The question changed when I answered, so this corresponds to the question that is now:

my_array.map.with_index{ |e,i| (e.nil?) ? nil  : i }.compact
 => [0, 1, 2, 5, 7] 

This is just a case of switching the values ​​of the ternary operator around.

And again the question has changed. With 1.8.7 and 1.9.2:

ruby-1.8.7-p330 :004 > my_array.each_with_index.map{|e,i| (e.nil?) ? nil : i }.compact
 => [0, 1, 2, 5, 7] 

ruby-1.9.2-p136 :002 > my_array.each_with_index.map{|e,i| (e.nil?) ? nil : i }.compact
 => [0, 1, 2, 5, 7] 
+4
source

I am sure there is a faster way, but:

result = []
my_array.each_with_index do |item, index|
  result << index unless item.nil?
end
+2
source

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


All Articles