zoukankan      html  css  js  c++  java
  • 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中的条件判断语句:

    1. if 语句

    =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

    2. unless 语句,其恰好与if语句相反,当条件不符合时,则执行相应语句

    =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.

    3. case 语句
    当同一个对象,要与多个值进行比较时,可以使用case语句,其功能与JAVA中的switch语句类似

    =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
    #这里比较的是对象的类型,而不是对象的值

    PS:
    if修饰符和unless修饰符可以写在执行语句后面,例如,print "a is larger than b." if a>b,所以ruby是很灵活的。

    "==="符号的意义,其在不同的场合可以代表不同的符号,若左边是数字或字符串时,则和"=="是一样的;在正则表达式的场合下则相当于"=~";在类的场合下,判断"==="右边的对象是否是类的实例

    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
  • 相关阅读:
    二进制运算
    python魔法函数__dict__和__getattr__的妙用
    logging模块配置笔记
    一个python爬虫工具类
    和我一起学爬虫(一)
    不一样的谷歌搜索
    CentOS6.4安装辅助NIS的流程
    ROS6.16开始支持802.11ac了,扫盲下
    centos 安装 Splunk
    扫盲贴2.5寸移动硬盘的厚度有几种
  • 原文地址:https://www.cnblogs.com/windy1118/p/RubyLearning5.html
Copyright © 2011-2022 走看看