2014-09-21 60 views
1

使用array.each_with_index返回一个数组,其中包含几个元素的索引,我将其设置为等于变量indexes。我只想知道如何在array[indexes] #=> element 1, element 2, etc这些索引中找到各个元素。我尝试了前面的例子,没有运气,也array[indexes.each {|x| x}]使用索引数组查找元素(Ruby)

不知道为什么这么难,但我是全新的编码,我无法在其他地方找到答案。

+0

给您已经尝试的代码。 – 2014-09-21 14:56:21

回答

3

这就是Array#values_at是:

indices = [0,2] 
p ["a", "b", "c", "a"].values_at(*indices) # => ["a", "c"] 
+0

这实际上是我在找的东西,我允许我做我需要的东西。谢谢! – 2014-09-21 15:28:03

0

您可能是错误的。

each_with_index意味着遍历你的阵列像这样的指标:

array.each_with_index do |element, index| 

#do stuff with the element and the index here 

end 

如果你已经有索引的数组,你真的想这样做的,您可以:

indexes.each do |index| 

array[index] 

end 

您应该将each作为for循环的其他元素,将每个元素连续传递给| |中的变量。在{ }do ... end内部,您可以使用自己的元素进行操作。它并不意味着像使用X = array.each :)

+0

当我说我使用'array.each_with_index'时,我刚刚离开了我用来查找我想要的索引的块的其余部分。应该保持清楚。您的解决方案有效,非常感谢! – 2014-09-21 15:06:11