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


TAG: Ruby

 

评分:0

我来说两句

我的栏目

日历

« 2024-04-29  
 123456
78910111213
14151617181920
21222324252627
282930    

数据统计

  • 访问量: 22742
  • 日志数: 47
  • 建立时间: 2008-01-29
  • 更新时间: 2008-02-02

RSS订阅

Open Toolbar