1
2
3
4
5
6
7
#!/usr/bin/env ruby

sum = 0
for i in 1..100 do
sum + = i
end
puts sum

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env ruby

sum = 0
i = 0
while i <= 100 do
sum = sum + i
i = i + 1
end

puts sum

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env ruby

sum = 0
i = 0
until i > 100 do
sum = sum + i
i = i + 1
end

puts sum

1
2
3
4
5
6
7
#!/usr/bin/env ruby

sum = 0
100.times {|num|
sum = sum + num
}
puts sum

1
2
3
4
5
6
7
8
#!/usr/bin/env ruby

sum = 0
(1..100).each{|num|
sum = sum + num
}

puts sum

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/env ruby

sum = 0
i = 0
loop {
i = i + 1
if i > 100
break
end
sum = sum + i
}

puts sum

loop 中提供了三种特殊运算方法:

1、上述的 break,直接跳出 loop

2、next,跳过当前 loop,如果 next 在 loop 循环体最下面,结果和不写 next 一样

3、redo,表示重新进行当前循环

loop计算1加到100,跳过50的写法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/usr/bin/env ruby

sum = 0
i = 0
loop {
i = i + 1
if i == 50
break
end
if i > 100
break
end
sum = sum + i
}

puts sum

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/usr/bin/env ruby

sum = 0
i = 0

loop {
i = i + 1
if i == 50
redo
end

if i > 100
break
end
sum = sum + i
}

puts sum

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/env ruby

sum = 0
i = 0

loop {
i = i + 1
if i == 50
next
end

if i > 100
break
end

sum = sum + i
}

puts sum