源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Ruby简明教程之判断语句介绍

  • 时间:2021-06-08 19:06 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Ruby简明教程之判断语句介绍
条件判断,在编程语言中都存在,而Ruby中的条件判断和Java中类似,当然还是存在些许差别 Ruby中条件判断的条件: 1) 可以使用 ==,<,>等比较运算来作为条件,比较运算可以返回true和false,这和java中的语法是类似的 2) 一些其他的方法也可以用来作为判断条件,比如,empty?方法,为空则返回true,否则返回false 3) 有些方法虽然不会返回true或false,但是也能作为条件判断的条件,他们返回的对象,要么是false或nil,要么是意义的对象,则可根据如下表格判断:
TRUE FALSE
false和nil以外的对象 false与nil
p /Ruby/ =~ "Ruby"  返回0,则在条件判断中可以返回true Ruby中也可以使用常用的逻辑运算符,&&,||,!,其代表的意义与JAVA中的意义是一致的。 Ruby中的条件判断语句: [b]1. if 语句 [/b]
[u]复制代码[/u] 代码如下:
=begin 语法: if 条件1 then    语句1 elsif 条件2 then    语句2 elsif 条件3 then    语句3 else    语句4 end =end a = 10 b = 20 if a>b then    print "a is smaller than b." elsif a == b then    print "a equals b." else    print "a is larger than b." end
[b]2. unless 语句[/b],其恰好与if语句相反,当条件不符合时,则执行相应语句
[u]复制代码[/u] 代码如下:
=begin 语法: unless 条件 then    语句 end =end a = 10 b = 20 unless a>b then    print "a is smaller than b." end # -> "a is smaller than b" will be printed out.
[b]3. case 语句 [/b]当同一个对象,要与多个值进行比较时,可以使用case语句,其功能与JAVA中的switch语句类似
[u]复制代码[/u] 代码如下:
=begin 语法: case 想要比较的对象 when 值1 then     语句1 when 值2 then     语句2 when 值3 then     语句3 else     语句4 end # then是可以省略的 =end array = ["aa", 1, nil] item = array[0]    case item    when String       puts "item is a String."    when Numeric       puts "item is a Numeric."    else       puts "item is a something"    end #这里比较的是对象的类型,而不是对象的值
[b]PS: [/b]if修饰符和unless修饰符可以写在执行语句后面,例如,print "a is larger than b." if a>b,所以ruby是很灵活的。 "==="符号的意义,其在不同的场合可以代表不同的符号,若左边是数字或字符串时,则和"=="是一样的;在正则表达式的场合下则相当于"=~";在类的场合下,判断"==="右边的对象是否是类的实例
[u]复制代码[/u] 代码如下:
p ((1..3) === 2)  #-> true p /zz/ === "zyzzy"  #-> 2 p String === "xyzzy"  # -> true #在case表达与if语句间转换,用===,符号左边是case的值,右边为case的变量 case A when value1                   if value1 === A    语句1                              语句1 when value2                   elsif value2 === A    语句2                               语句2 else                                else    语句3                                语句3 end                                 end
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部