在Ruby中,循環(huán)結構主要有兩種:each
和while
。這些循環(huán)結構可以與其他語句搭配使用,例如條件語句、變量聲明和函數調用等。以下是一些示例:
each
循環(huán)遍歷數組并計算元素之和:numbers = [1, 2, 3, 4, 5]
sum = 0
numbers.each do |number|
sum += number
end
puts "The sum is: #{sum}"
while
循環(huán)計算階乘:n = 5
factorial = 1
while n > 0
factorial *= n
n -= 1
end
puts "The factorial of #{n} is: #{factorial}"
numbers = [1, 2, 3, 4, 5]
numbers.each do |number|
if number % 2 == 0
puts "#{number} is even"
else
puts "#{number} is odd"
end
end
i = 0
while i < 5
puts "Iteration: #{i}"
i += 1
end
def print_hello(name)
puts "Hello, #{name}!"
end
names = ["Alice", "Bob", "Carol"]
names.each do |name|
print_hello(name)
end
這些示例展示了如何在Ruby中使用循環(huán)結構與其他語句搭配。你可以根據自己的需求調整代碼,以實現所需的功能。