Ruby语言基础学习四:Ruby 条件、循环
2016-04-02 16:56
537 查看
#_*_ coding:utf-8 _*_ x=1 if x>2 puts "x bigger than 2" elsif x<=2 and x!=0 puts "x is 1" else puts "can not get the value of x." end # 通常我们省略保留字 then 。若想在一行内写出完整的 if 式, # 则必须以 then 隔开条件式和程式区块 if x==1 then puts "don't omit the then" end # Ruby if 修饰符 # if修饰词组表示当 if 右边之条件成立时才执行 if 左边的式子。即如果 conditional 为真,则执行 code $debug=1 print "debug\n" if $debug #很简单的条件句 # Ruby unless 语句 # unless式和 if式作用相反,即如果 conditional 为假,则执行 code。如果 conditional 为真,则执行 else 子句中指定的 code。 x=1 unless x>2 #除非x>2,否则执行下面这句,相反情况则执行else后面的 puts "x is less then 2" else puts "x is biger than 2" end # Ruby unless 修饰符 $var=1 print "1--this line print out\n" if $var print "2--this line not print out \n" unless $var $var=false print "3--this line print out" unless $var # Ruby case 语句 # 通常我们省略保留字 then 。若想在一行内写出完整的 when 式,则必须以 then 隔开条件式和程式区块。 case a=1 #这里还是要加case的 when a==1 then a=7 end $age=5 case $age when 0..2 puts "baby" when 3..6 puts "little child" when 7..12 puts "child" when 13..16 puts "teenage" else puts "Other age" end foo=false bar=true quu=false # 当case的"表达式"部分被省略时,将计算第一个when条件部分为真的表达式。 case when foo then puts 'foo is true' when bar then puts 'bar is true' when quu then puts 'quu is true' end # Ruby 中的循环用于执行相同的代码块若干次。 $i=0 $num=5 # 语法中 do 或 : 可以省略不写。但若要在一行内写出 while 式,则必须以 do 或 : 隔开条件式或程式区块。 while $i<$num do puts " in circle line i=#{$i}" $i +=1 end # Ruby while 修饰符 # 如果 while 修饰符跟在一个没有 rescue 或 ensure 子句 # 的 begin 语句后面,code 会在 conditional 判断之前执行一次。 #puts "I love you !" while true $flag=0 begin puts "I love you too!" $flag+=1 end while $flag>5 #注意这里的flag前面加$ # Ruby until 修饰符 $i=0 $num=5 begin puts("在until循环语句中 i = #$i") $i+=1 end until $i>$num # Ruby for 语句 for i in 0..5 do #其中do在这里可以省略 puts "for循环局部变量的值为 #{i}" end # for...in 循环几乎是完全等价于: (0..5).each do |i| puts "each循环局部变量的值为 #{i}" end #break 语句 for i in 0..5 if i>2 then break end puts "break循环局部变量的值为 #{i}" end # Ruby next 语句,就相当于其他语言中的continue语句 for i in 0..5 if i<2 then next end puts "next循环局部变量的值为 #{i}" end #Ruby redo 语句 # 重新开始最内部循环的该次迭代,不检查循环条件。如果在块内调用,则重新开始 yield 或 call。 for i in 0..5 if i<2 then puts "局部变量的值为 #{i}" #redo #如果这里加redo会进入死循环 end end # Ruby retry 语句 #ruby1.9以上,retry只能支持在rescue里面使用,不支持在block里面用; n = 0 begin puts 'Trying to do something' raise 'oops' rescue => ex puts ex n += 1 retry if n < 3 end puts "Ok, I give up"
相关文章推荐
- Ruby语言基础学习三:Ruby变量、运算
- Ruby语言基础学习二:Ruby类、变量、常量、伪变量
- Ruby语言基础学习一:Ruby语法和数据类型
- RubyMine常用快捷键
- gem install sass 本地配置和淘宝源无效的解决办法
- 如何在Mac OS X上安装 Ruby运行环境
- pry与ruby版本冲突
- /ruby-2.0.0-p643/bin/rails:23:in `load': cannot load such file
- Ruby--加载文件--require和require_relative
- Ruby之入门(一)
- rails/ruby 查找类的方法
- Ruby--如何处理csv文件?
- Ruby中Time对象的常用函数总结
- Ruby的字符串与数组求最大值的相关问题讨论
- ubuntu下安装RubyMine
- Ruby自学之路 二
- ERB预处理ruby代码
- 关于Ruby, Ruby on Rails的一些概念属性的介绍
- Ruby自学之路 一
- cocoaPod使用进阶