是否有类似于Java/C(++)的for循环的Ruby版本?是否有类似于Java/C++的for循环的Ruby版本?
在Java:
for (int i=0; i<1000; i++) {
// do stuff
}
的原因是因为我需要根据迭代的指数做不同的操作。看起来Ruby只有一个for-each循环?
我正确吗?
是否有类似于Java/C(++)的for循环的Ruby版本?是否有类似于Java/C++的for循环的Ruby版本?
在Java:
for (int i=0; i<1000; i++) {
// do stuff
}
的原因是因为我需要根据迭代的指数做不同的操作。看起来Ruby只有一个for-each循环?
我正确吗?
是的,你可以在每次迭代
您可以通过用户each with index使用each_with_index
的“索引”变量给你的元素索引。
在Ruby中,for
回路可以实现为:
1000.times do |i|
# do stuff ...
end
如果你想同时得到元素和索引,则each_with_index
语法可能是最好的:
collection.each_with_index do |element, index|
# do stuff ...
end
然而each_with_index
环因为它为循环的每次迭代提供了element
和index
对象,所以速度较慢。
Ruby倾向于使用迭代器而不是循环;您可以使用Ruby强大的迭代器获取所有循环函数。
有几种选择,要做到这一点,让我们假设你有一个数组“改编”大小的1000
1000.times {|i| puts arr[i]}
0.upto(arr.size-1){|i| puts arr[i]}
arr.each_index {|i| puts arr[i]}
arr.each_with_index {|e,i| puts e} #i is the index of element e in arr
所有这些例子都提供相同的功能
我会补充说,你也可以使用for循环,如下所示:for i in(0。 ..arr.length);放置arr [i];结束 – philosodad 2012-05-19 12:36:03
如何step
?
0.step(1000,2) { |i| puts i }
等同于:
for (int i=0; i<=1000; i=i+2) {
// do stuff
}
times
建议在each_with_index
。 times
快6倍左右。运行下面的代码。
require "benchmark"
TESTS = 10_000_000
array = (1..TESTS).map { rand }
Benchmark.bmbm do |results|
results.report("times") do
TESTS.times do |i|
# do nothing
end
end
results.report("each_with_index") do
array.each_with_index do |element, index|
# Do nothing
end
end
end
我用我的MacBook(Intel Core2Duo)得到了如下结果。
Rehearsal ---------------------------------------------------
times 1.130000 0.000000 1.130000 ( 1.141054)
each_with_index 7.550000 0.210000 7.760000 ( 7.856737)
------------------------------------------ total: 8.890000sec
user system total real
times 1.090000 0.000000 1.090000 ( 1.099561)
each_with_index 7.600000 0.200000 7.800000 ( 7.888901)
您没有访问'times'基准测试中的数组元素 - 您正在比较数组查找和空循环 – user214028 2009-12-09 11:17:43
当我需要的只是数字(和不想重复),我更喜欢这样的:
(0..10000).each do |v|
puts v
end
while循环,只要条件为真执行其身体零次或多次。
while <condition>
# do this
end
while循环可以替代Java的'for'循环。 在Java中,
for (initialization;, condition;, incrementation;){
//code
}
是相同如下(除,在第二形式中,初始化变量不是本地的for循环)。
initialization;
for(, condition;,) {
//code
incrementation;
}
ruby'while'循环可以写成这种形式来作为for循环的Java。在Ruby中,
initialization;
while(condition)
# code
incrementation;
end
请注意'while'(和'until'和'for')循环不会引入新的作用域;先前存在的本地人可以在循环中使用,并且新创建的本地人将在之后可用。
for i in 0..100 do
#bla bla
end
'each_with_index'不会比为每个元素进行数组查找慢。它应该快得多。 – Chuck 2009-12-09 06:40:10
正确,但是如果您没有为循环的每次迭代执行数组查找,'each_with_index'可能会变慢。它最终取决于循环当然。 – erik 2009-12-09 14:54:28
嗯,是的,如果你不使用数组,显然你不会想要使用数组方法... – Chuck 2009-12-09 20:25:32