zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    机器学习数据
    偏差和方差
    numpy基础
    卷积神经网路
    深度学习基础
    Iris数据集
    SVM-SVR
    Java之日期处理
    MySQL笔记
    在Eclipse中运行的时候出现launching/Building
  • 原文地址:https://www.cnblogs.com/timsheng/p/2582643.html
Copyright © 2011-2022 走看看