在Ruby中,循环结构主要有两种:each
和while
。这些循环结构可以与其他语句搭配使用,例如条件语句、变量声明和函数调用等。以下是一些示例:
each
循环遍历数组并计算元素之和:numbers = [1, 2, 3, 4, 5]
sum = 0
numbers.each do |number|
sum += number
end
puts "The sum is: #{sum}"
while
循环计算阶乘: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中使用循环结构与其他语句搭配。你可以根据自己的需求调整代码,以实现所需的功能。