Ruby 控制结构

Ruby具有所有常见的控制结构,如if语句和while循环。Java、C和Perl 程序员可能会对这些语句的程序体“缺乏花括号”不太适应。Ruby是使用end关键字来表明程序体的结束。

if count>10

 puts "try again"

elsif tries==3

 puts "You lose"

else

 puts "Enter a number"

end

同样地,while语句以end结束。

while weight <100 and num_pallets <=30

 pallet = next_pallet()

 weight += pallet.weight

 num_pallets +=1

end
如果if 或while语句的程序体只是一个表达式,Ruby的语句修饰符(statement modifiers)是一种有用的快捷方式。只要写出表达式,后面跟着if或while和条件。比如,这是if语句的例子。

if radiation > 3000

 puts "Danger, Will Robinson"

end

用语句修饰符重新编写了同样这个例子。

puts "Danger, Will Robinson" if radiation > 3000

同样地,下面是while循环语句

square = 2

while square <1000

 square = square*square

end

用语句修饰符,这个语句变得更简洁了。

square = 2

square = square*square while square<1000

 

posted on 2012-07-09 14:12  tim_sheng  阅读(172)  评论(0编辑  收藏  举报

导航