rya*_*ogo 10 ruby java foreach for-loop
是否存在类似于Java/C(++)中的for循环的Ruby版本?
在Java中:
for (int i=0; i<1000; i++) {
// do stuff
}
Run Code Online (Sandbox Code Playgroud)
原因是我需要根据迭代索引进行不同的操作.看起来Ruby只有for-each循环?
我对么?
小智 15
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
Run Code Online (Sandbox Code Playgroud)
所有这些示例都提供相同的功能
nas*_*nas 11
是的,您可以使用each_with_index
collection = ["element1", "element2"]
collection.each_with_index {|item,index| puts item; puts index}
Run Code Online (Sandbox Code Playgroud)
'index'变量在每次迭代期间为您提供元素索引
dra*_*tun 10
怎么样step?
0.step(1000,2) { |i| puts i }
Run Code Online (Sandbox Code Playgroud)
相当于:
for (int i=0; i<=1000; i=i+2) {
// do stuff
}
Run Code Online (Sandbox Code Playgroud)
只要其条件为真,while 循环就会执行其主体零次或多次。
while <condition>
# do this
end
Run Code Online (Sandbox Code Playgroud)
while 循环可以替代 Java 的“for”循环。在爪哇,
for (initialization;, condition;, incrementation;){
//code
}
Run Code Online (Sandbox Code Playgroud)
与以下相同(除了在第二种形式中,初始化变量不是 for 循环的局部变量)。
initialization;
for(, condition;, ) {
//code
incrementation;
}
Run Code Online (Sandbox Code Playgroud)
ruby 'while' 循环可以用这种形式编写,作为 Java 的 for 循环。在红宝石中,
initialization;
while(condition)
# code
incrementation;
end
Run Code Online (Sandbox Code Playgroud)
请注意,“while”(以及“until”和“for”)循环不会引入新的作用域;先前存在的本地人可以在循环中使用,之后创建的新本地人将可用。
在Ruby中,for循环可以实现为:
1000.times do |i|
# do stuff ...
end
Run Code Online (Sandbox Code Playgroud)
如果你想要元素和索引,那么each_with_index语法可能是最好的:
collection.each_with_index do |element, index|
# do stuff ...
end
Run Code Online (Sandbox Code Playgroud)
但是each_with_index循环速度较慢,因为它为循环的每次迭代提供了对象element和index对象.