ruby系列教材(4):Control Structures
上一篇 /
下一篇 2008-02-02 14:44:03
/ 个人分类:Ruby
ruby 有通常的控制结构:if语句和while循环,它们没有{},使用end作为结束:
1.if
if count > 10
puts "Try again"
elsif tries == 3 #使用 elsif 而不是else if
puts "You lose"
else
puts "Enter a number"
end
2.while
while weight < 100 and num_pallets <= 30 #使用 and 表示"与"
pallet = next_pallet()
weight += pallet.weight
num_pallets += 1
end
while line = gets #使用while读取文件,gets方法在读取文件时,遇见文件尾返回nil,正如前面所说的,nil表示false
puts line.downcase
end
3.statement modifier:一种编程的捷径
if radiation > 3000
puts "Danger, Will Robinson"
end
使用 statement modifer 重写以后:puts "Danger, Will Robinson" if radiation > 3000
它也表示了同样的效果,while也可以
square = 2
while square < 1000
square = square*square
end
使用 statement modifer 重写以后:
square = 2
square = square*square while square < 1000
循环被简化成为一行
http://www.i170.com/user/killercat/Article_30647
相关阅读:
- Ruby学习总结三 (夜来烧, 2008-1-23)
- Understanding Ruby blocks, Procs and methods (夜来烧, 2008-1-23)
- Deaf Grandma Program (夜来烧, 2008-1-24)
- Ruby学习总结四 (夜来烧, 2008-1-25)
- Ruby学习总结五 (夜来烧, 2008-1-29)
- Ruby学习总结六 (夜来烧, 2008-1-29)
- 三个输出方法 (夜来烧, 2008-2-02)
- ruby系列教材(1):Ruby Is an Object-Oriented Language (snake007008009, 2008-2-02)
- ruby系列教材(2):Some Basic Ruby (snake007008009, 2008-2-02)
- ruby系列教材(3):Arrays and Hashes (snake007008009, 2008-2-02)
收藏
举报
TAG:
Ruby