【问题标题】:Get the indice of array if some condition is met in Ruby [duplicate]如果在Ruby中满足某些条件,则获取数组的索引[重复]
【发布时间】: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


【解决方案1】:

这可能是重复的,但快速搜索未找到任何内容。

最简单的方法大概是使用each_with_index:

irb(main):001:0> a=[32,35,68,44,8,45] #=> [32, 35, 68, 44, 8, 45]
irb(main):002:0> a.each_with_index.select { |n,i| n > 35 }.map &:last     
=> [2, 3, 5]

【讨论】:

  • 马克,如果你迟到 10 秒就好了:)
  • 替代:a.map.with_index{ |n,i| n>35 ? i : nil }.compact
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-11
  • 2023-03-08
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
相关资源
最近更新 更多