Arrays 在数组ruby中寻找元素的索引
如何在ruby中找到具有特定值的数组中所有元素的索引?Arrays 在数组ruby中寻找元素的索引,arrays,ruby,Arrays,Ruby,如何在ruby中找到具有特定值的数组中所有元素的索引? 也就是说,如果你有一个数组[2,3,52,2,4,1,2],有没有比使用循环更简单的方法来获取数组中所有2的索引?如果我要找2的话,答案应该是[0,3,6] 答案在 如果我只想找到给定元素的一个实例,则给出解决方案。试试这个 arr = [2,3,52,2,4,1,2] output = [] arr.each_with_index do |v,i| if v == 2 output <
也就是说,如果你有一个数组[2,3,52,2,4,1,2],有没有比使用循环更简单的方法来获取数组中所有2的索引?如果我要找2的话,答案应该是[0,3,6]
答案在 如果我只想找到给定元素的一个实例,则给出解决方案。试试这个
arr = [2,3,52,2,4,1,2]
output = []
arr.each_with_index do |v,i|
if v == 2
output << i
end
end
puts output #=> [0, 3, 6]
arr=[2,3,52,2,4,1,2]
输出=[]
每一个带有指数do,v,i的|
如果v==2
输出[0,3,6]
a
# => [2, 3, 52, 2, 4, 1, 2]
b=[]
# => []
a、 每个| u与| i,ind | b[2,3,52,2,4,1,2]
也许你可以用这个:
a = [2, 3, 52, 2, 4, 1, 2]
b = a.map.with_index{|k, i| i if k == 2}.compact
b
# => [0,3,6]
或者,如果您想修改一个变量,那么请修改版本
a = [2, 3, 52, 2, 4, 1, 2]
a.map!.with_index{|k, i| i if k == 2}.compact!
a
# => [0,3,6]
我觉得还是有捷径的
另一种选择可能是:
a.each_with_object([]).with_index {|(i, result), index| result << index if i == 2 }
a.each_与_对象([])。与_索引{|(i,结果),index | result谢谢你。我得到了一个简化版,它工作得很好!这无法按照你的要求获得输出。Luka或Rick的答案可能是你想要的。你检查数组b了吗…?我忘记粘贴输出了。请自己检查一次,因为它是b
你正在构建的,为什么要使用map
?您正在将a
映射到一个您不使用的数组。难道a.每个索引为
的数组都更直接吗?@CarySwoveland我在本例中修改了map的用法。您是对的,我在本例中使用它“uncorrect”。
a.each_with_object([]).find_all {|i, index| i == 2}.map {|i, index| index }
a.each_with_object([]).with_index {|(i, result), index| result << index if i == 2 }
a = [2,3,52,2,4,1,2]
a.each_index.select { |i| a[i]== 2 }
#=> [0, 3, 6]