在Ruby中,循環結構主要有兩種:each
和each_with_index
。這里有一些實用的技巧:
each
循環遍歷數組或集合:array = [1, 2, 3, 4, 5]
array.each do |element|
puts element
end
each_with_index
循環遍歷數組或集合,同時獲取元素及其索引:array = ['a', 'b', 'c', 'd', 'e']
array.each_with_index do |element, index|
puts "Element at index #{index}: #{element}"
end
times
方法創建一個指定次數的循環:number = 5
number.times do
puts "This is loop iteration number #{index}"
end
while
循環:counter = 0
while counter < 5
puts "Counter: #{counter}"
counter += 1
end
for
循環(在Ruby中較少使用,但在某些情況下可能更清晰):for i in 1..5
puts "Iteration: #{i}"
end
break
和next
提前跳出循環:array = [1, 2, 3, 4, 5]
array.each do |element|
if element == 3
break
end
puts element
end
retry
重新嘗試循環中的代碼塊:retries = 0
begin
result = 10 / 0
rescue ZeroDivisionError
retries += 1
retry if retries < 3
puts "Too many retries"
end
ensure
子句確保在循環結束時執行某些操作:array = [1, 2, 3, 4, 5]
array.each do |element|
if element == 3
puts "Found the number 3, breaking the loop"
break
end
ensure
puts "Loop completed"
end
這些技巧可以幫助您更有效地使用Ruby的循環結構。