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