使用索引数组查找数组的元素(Ruby)

时间:2014-09-21 14:49:10

标签: ruby arrays indexing

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

不确定为什么这么难,但我对编码很陌生,我无法在其他地方找到答案。

2 个答案:

答案 0 :(得分:3)

这就是Array#values_at的用途:

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

答案 1 :(得分: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那样使用:)