获取数组中所有值为 nil 的索引

get all indexes of value nil in array

我有一个 N 元素的数组,这个数组包含 01nil。 我想获取 nil 所在的所有索引或对数组进行排序,以便所有 nil 排在第一位。

我正在寻找一种有效的方法,因为数组大小可能非常大。

这是我的代码

array_of data # array with lots of 1, 0 and nil
temp = []
array_of_data.each_with_index {|a,i| (array_of_data[i] ? true : temp << i )}

供您进行基准测试的备选方案:

# Indices of non-nil values
res = ary.map.with_index{ |v,i| i if v }.compact
res = [].tap{ |r| ary.each.with_index{ |v,i| r<<i if v } }
ary.map!.with_index{ |v,i| v && i }.compact

# Sorting the array so that nil comes first (possibly re-ordering the others)
res = ary.sort_by{ |v| v ? 1 : -1 }
ary.sort_by!{ |v| v ? 1 : -1 }

# Sorting the array so that nil comes first, order of others unchanged
res = ary.sort_by.with_index{ |v,i| v ? i : -1 }
ary.sort_by!.with_index{ |v,i| v ? i : -1 }