» Ruby快速入门 » 1. 基础篇 » 1.4 控制流

控制流

Ruby提供了几种控制结构来管理代码的执行流。

条件语句

if...elsif..else

x = 10

if x > 5
  puts "x is greater than 5"
elsif x == 5
  puts "x is equal to 5"
else
  puts "x is less than 5"
end

unless

x = 10

unless x > 5
  puts "x is not greater than 5"
else
  puts "x is greater than 5"
end

Case 语句

day = "Wednesday"

case day
when "Monday"
  puts "It's Monday"
when "Wednesday", "Friday"
  puts "It's a midweek day"
else
  puts "It's another day"
end

循环

while

counter = 0

while counter < 5
  puts counter
  counter += 1
end

until

counter = 0

until counter >= 5
  puts counter
  counter += 1
end

for

for i in 0..4
  puts i
end

each

each 用于迭代集合。

fruits = ["apple", "banana", "orange"]

fruits.each do |fruit|
  puts fruit
end

迭代器

times

5.times do
  puts "Hello, World!"
end

upto & downto

1.upto(5) do |num|
  puts num
end

5.downto(1) do |num|
  puts num
end

each_with_index

fruits = ["apple", "banana", "orange"]

fruits.each_with_index do |fruit, index|
  puts "#{index + 1}. #{fruit}"
end

代码挑战

完美数是一个正整数,等于其除自身之外的真因子之和。
编写一个Ruby函数,查找限制范围内的完美数。

Loading...
> 此处输出代码运行结果
上页
下页