-2

I want to move through just two indexes of an array. Something along these lines

iterate_amount = 2
array = [2,4,6,7]

iterate_amount.times do |x|
    puts x
end #=> 2,4

I just don't know how I can place the 'array' in the loop to tell the interpreter this is the array I want to move through two indexes.

4

2 回答 2

4

您可以使用Enumerable#cycle

array = [2,4,6,7]
array.cycle(2) do |x|
  puts x
end

印刷

2
4
6
7
2
4
6
7

更新

Array#[]与指定开始、长度或指定范围一起使用。

>> array[0, 2]
=> [2, 4]
>> array[0..1]
=> [2, 4]
>> array[0...2]
=> [2, 4]
于 2013-10-09T11:05:05.297 回答
1

使用Array#take http://ruby-doc.org/core-2.0.0/Array.html#method-i-take

>> a = [2,4,6,7]
=> [2, 4, 6, 7]
>> a.take 2
=> [2, 4]
于 2013-10-09T11:15:30.183 回答