簡體   English   中英

是否有類似於Java / C ++的Ruby版本的for循環?

[英]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循環較慢,因為它為循環的每次迭代提供了elementindex對象。

只要條件為真,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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM