zoukankan      html  css  js  c++  java
  • ruby编程语言-学习笔记5(第5章 语句和控制结构)

    以下是2种表达方式一样。

    if expression
      code
    end
    if expression then     #推荐这种形式
      code
    end

    expression的值不是false或nil,则code块将被执行。

    需要注意:1)围绕expressions的圆括号是可选的(而且通常都不用),ruby使用换行符、分号或者关键字then对条件表达式和后续的内容进行分隔

         2) 必须以end 作为结束。

    例子

    if data      #if array exist
      data << x   #append  x to data
    else        
      data = [x]   #create a new array, that holds the value
    end        #this is the end of the conditional
    if expression_1 then    
      code1
    elseif expression_2
      code2
    .....
    elseif expression_N
      code3
    else
      code
    end

    例子 (多种形式,最好使用同一种代码规范)个人认为then最好

    if  x==1
      name = "one"
    elseif x==2
      name = "two"
    elseif x==3 then name ="three"
    elseif x==4; name = "four"
    else
      name = "many"
    end

    5.1.3 返回值

    在大多数语言中if条件式是一个语句,但在ruby中一切都是表达式,包括那些被称为语句的控制结构。

    if“语句”的返回值:为被执行代码中最后一个表达式的值,若没有任何执行代码则返回nil

    name = if  x==1    then  "one"
        elseif x==2 then  "two"
        elseif x==3 then "three"
        elseif x==4; then "four"
        else         "many"
        end    

    5.1.2 修饰符if

    code if expression

    puts message if message    #if message not nil, or false, print  it

     if修饰符的优先级很低,比赋值操作符还低

    y = x.invert  if x.respond_to ? :invert   #if修饰符作用与整个赋值表达式,如果x没有名为invert的方法,那么不会有任何事情发生。

    y = (x.invert  if x.respond_to ? :invert)  #if修饰符仅仅作用与方法调用,如果if没有invert方法,那么该修饰符表达式的值将为nil,然后这个值被赋给y.

  • 相关阅读:
    友盟上报 IOS
    UTF8编码
    Hill加密算法
    Base64编码
    Logistic Regression 算法向量化实现及心得
    152. Maximum Product Subarray(中等, 神奇的 swap)
    216. Combination Sum III(medium, backtrack, 本类问题做的最快的一次)
    77. Combinations(medium, backtrack, 重要, 弄了1小时)
    47. Permutations II(medium, backtrack, 重要, 条件较难思考)
    3.5 find() 判断是否存在某元素
  • 原文地址:https://www.cnblogs.com/scotth/p/3164455.html
Copyright © 2011-2022 走看看