Preface
Loops in Ruby are used to execute the same block of code a specified number of times. This chapter details all the loop statements supported by Ruby.
while、until、loop 與 for
while 迴圈根據所指定的條件式來判斷是否執行迴圈本體,例如以下是個求最大公因數的程式:
- # encoding: Big5
- puts "輸入兩個數字..."
- m = gets.to_i
- n = gets.to_i
- while n != 0
- r = m % n
- m = n
- n = r
- end
- puts "GCD: #{m}"
- # encoding: Big5
- begin
- print "輸入數字:"
- printf "輸入數為 %s\n", gets.to_i % 2 == 0 ? "偶數" : "奇數"
- print "繼續?(Yes/No)"
- end while gets.chomp == "Yes"
- n = 1
- n = (rand() * 10).to_i while n % 2 == 1
- print n
- # encoding: Big5
- puts "輸入兩個數字..."
- m = gets.to_i
- n = gets.to_i
- until n == 0
- r = m % n
- m = n
- n = r
- end
- puts "GCD: #{m}"
- # encoding: Big5
- begin
- print "輸入數字:"
- printf "輸入數為 %s\n", gets.to_i % 2 == 0 ? "偶數" : "奇數"
- print "繼續?(Yes/No)"
- end until gets.chomp == "No"
- n = 1
- n = (rand() * 10).to_i until n % 2 != 1
- print n
- # encoding: Big5
- loop { print "永不停止的 Orz..." }
- # encoding: Big5
- 10.times do |i|
- puts "第 #{i + 1} 次的 Orz..."
- end
- # encoding: Big5
- [1, 2, 3, 4, 5].each do |element|
- print element
- end
- puts
- for element in [1, 2, 3, 4, 5]
- print element
- end
- # encoding: Big5
- loop do
- print "輸入數字:"
- number = gets.to_i
- printf "輸入數為 %s\n" % (number % 2 == 0 ? "偶數" : "奇數")
- print "繼續?(Yes/No)"
- if gets.chomp == "No"
- break
- end
- end
- # 底下顯示 1234
- for i in 1..9
- if i == 5
- break
- end
- print i
- end
- puts
- # 底下顯示 12346789
- for i in 1..9
- if i == 5
- next
- end
- print i
- end
redo是重作「一次redo前的區塊內容」(不是重作「一次迴圈」)。例如:
- # 底下顯示 1234redoredoredo....
- for i in 1..9
- if i == 5
- print "redo"
- redo
- end
- print i
- end
Supplement
* Ruby 手冊 - 控制結構
* Ruby tutorialspoint - Ruby Loops - while, for, until, break, redo and retry
沒有留言:
張貼留言