在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的循环结构。