在Ruby中,循環(huán)結(jié)構(gòu)主要有兩種:each
和each_with_index
。這些循環(huán)結(jié)構(gòu)的使用技巧如下:
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 #{self}"
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
array = [1, 2, 3, 4, 5]
array.each_with_index do |element, index|
if index == 2
next
end
puts "Element at index #{index}: #{element}"
end
retry
和raise
在循環(huán)中處理異常:retries = 3
begin
# Your code that might raise an exception
raise "An error occurred"
rescue => e
retries -= 1
puts "Retrying... (#{retries} attempts left)"
retry if retries > 0
end
each_cons
和each_slice
在循環(huán)中處理子數(shù)組:array = [1, 2, 3, 4, 5]
array.each_cons(2).each do |sub_array|
puts "Sub-array: #{sub_array}"
end
array = [1, 2, 3, 4, 5]
array.each_slice(2).each do |sub_array|
puts "Sub-array: #{sub_array}"
end
這些技巧可以幫助您更有效地使用Ruby中的循環(huán)結(jié)構(gòu)。