Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 使用步长在数组中循环_Ruby_Loops_Iteration - Fatal编程技术网

Ruby 使用步长在数组中循环

Ruby 使用步长在数组中循环,ruby,loops,iteration,Ruby,Loops,Iteration,我想看看数组中的第n个元素。在C++中,我会这样做: for(int x = 0; x<cx; x+=n){ value_i_care_about = array[x]; //do something with the value I care about. } for(int x=0;x我们可以在每次迭代时跳过一系列数字进行迭代,例如: 1.step(10, 2) { |i| print "#{i} "} 比如: array.step(n) do |elemen

我想看看数组中的第n个元素。在C++中,我会这样做:

for(int x = 0; x<cx; x+=n){
    value_i_care_about = array[x];
    //do something with the value I care about.  
}

for(int x=0;x我们可以在每次迭代时跳过一系列数字进行迭代,例如:

1.step(10, 2) { |i| print "#{i} "}

比如:

array.step(n) do |element|
  # process element
end

范围有一个
步骤
方法,可用于跳过索引:

(0..array.length - 1).step(2).each do |index|
  value_you_care_about = array[index]
end
或者,如果您对使用
范围感到满意,则以下内容更为简洁:

(0...array.length).step(2).each do |index|
  value_you_care_about = array[index]
end

这是使用模运算符
%

当您掌握了这个概念后,就可以将其应用于大量不同的编程语言中,而不必对它们了如指掌

step = 2
["1st","2nd","3rd","4th","5th","6th"].each_with_index do |element, index|
  puts element if index % step == 1
end

#=> "2nd"
#=> "4th"
#=> "6th"
您可以将该方法添加到类数组中

,只需使用Range类中返回枚举数的step()方法即可

(1..10).step(2) {|x| puts x}
那么:

> [1, 2, 3, 4, 5, 6, 7].select.each_with_index { |_,i| i % 2 == 0 }
=> [1, 3, 5, 7]

迭代器的链接非常有用。

似乎谷歌可以回答这个问题,关于这一步的任何东西都可以找到:)每个。。或者for循环很容易找到。。我想做的是arrayBenjamin答案中的每一个第五、第十或第九元素都是不正确的。你应该看看Levi或David的答案。是的,
1是有道理的。步骤(3,2)
给出了1和3。在这段代码中,步骤是2,因此跳过第二个元素。这就剩下1和3了。顺便说一下,这与Rails无关,这是一个Ruby问题。你错过了这一步。这是很重要的一点。只是今晚感觉有点不舒服
Array
没有
step
方法,因此您将得到“未定义的step方法”<代码>1。步骤(10,2)
确实有效,但不会在数组上迭代。李维有正确的答案是的。。但是为了本的辩护。。这足以让我明白。Levi's也不会迭代数组。两个答案都很好,我不得不投你反对票。。。如果n是1000,那么我有10000个元素,我只做了10000个如果,我不需要得到10个元素,我只是想知道为什么它会被否决。。谢谢你让我知道你说的当然是对的。负面影响越大,你的步幅就越大。如果你像我刚才一样对此感到好奇,请参阅本文要点中的重要基准测试结果:卓越搜索dave。只要循环中有比较,每次都会运行。。如果你能让它脱离你的循环,它会运行得更快。我喜欢看我的自行车,让。。。。那么,我就用
替换我的
if
s,除非
。。。jk;)您可以使用
(0…array.length)
而不是
(0…array.length-1)
nice。不喜欢创建一百万个范围的想法,其中int将在C++中完成任务。但是库伦,也许,但在这种情况下,完全没有必要。只需使用select的块形式:
[1,2,3,4,5,6,7]。select(&:odd?)
(1..10).step(2) {|x| puts x}
> [1, 2, 3, 4, 5, 6, 7].select.each_with_index { |_,i| i % 2 == 0 }
=> [1, 3, 5, 7]