【发布时间】:2015-01-27 15:17:22
【问题描述】:
如果满足其元素的条件,我如何获取数组的所有索引的数组。例如:
a = [32, 35, 68, 44, 8, 45]
该方法应该返回一个数组[2, 3, 5],条件> 35。
【问题讨论】:
-
result = []; a.each.with_index {|e, i| result << i if e > 35} -
@iamnotmaynard - 使用
inject构造数组而不是在循环中逐步构建它会更加Rubyish。像这样的东西:result = a.each_with_index.inject([]) {|r,(e,i)| e > 35 ? r + [i] : r }
标签: ruby