[英]Is there a Ruby version of for-loop similar to the one on Java/C++?
是否有类似于Java / C(++)中的for循环的Ruby版本?
在Java中:
for (int i=0; i<1000; i++) {
// do stuff
}
原因是我需要根据迭代索引进行不同的操作。 看起来Ruby只有for-each循环?
我对么?
Ruby倾向于使用迭代器而不是循环; 你可以使用Ruby强大的迭代器获得循环的所有功能。
有几种选择,让我们假设你有一个大小为1000的数组'arr'。
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
所有这些示例都提供相同的功能
是的,您可以使用each_with_index
collection = ["element1", "element2"]
collection.each_with_index {|item,index| puts item; puts index}
'index'变量在每次迭代期间为您提供元素索引
step
怎么样?
0.step(1000,2) { |i| puts i }
相当于:
for (int i=0; i<=1000; i=i+2) {
// do stuff
}
在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
对象。
只要条件为真,while循环就会执行零次或多次。
while <condition>
# do this
end
while循环可以替换Java的'for'循环。 在Java中
for (initialization;, condition;, incrementation;){
//code
}
与以下相同(除了,在第二种形式中,初始化变量不是for循环的本地变量)。
initialization;
for(, condition;, ) {
//code
incrementation;
}
ruby'while'循环可以用这种形式编写,以用作Java的for循环。 在Ruby中,
initialization;
while(condition)
# code
incrementation;
end
请注意,'while'(和'until'和'for')循环不会引入新范围; 之前存在的本地人可以在循环中使用,之后创建的新本地人将可用。
for i in 0..100 do
#bla bla
end
您可以使用索引为每个用户。
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)
当我只需要数字(而不想迭代)时,我更喜欢这个:
(0..10000).each do |v|
puts v
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.