您现在的位置: 万盛学电脑网 >> 程序编程 >> 网络编程 >> 编程语言综合 >> 正文

解读Ruby当中的条件判断语句

作者:佚名    责任编辑:admin    更新时间:2022-06-22

   这篇文章主要介绍了详细解读Ruby当中的条件判断语句,if、else等逻辑判断语句是各门编程语言的基础,需要的朋友可以参考下

  Ruby的提供有条件结构,常见在现代编程语言中。在这里,我们将解释Ruby所有条件语句和修饰符

  Ruby if...else 语句:

  语法:

  ?

1 2 3 4 5 6 7 if conditional [then] code... [elsif conditional [then] code...]... [else code...] end

  if 表达式用于条件执行。值为false和nil都是假的,其它的都是true。注意Ruby串使用的是elsif,不是else if也不是elif。

  if 条件为ture则执行代码。如果条件不为ture,那么将执行else子句中指定的代码。

  if 表达式的条件是保留字,那么,一个换行符或分号分开代码。

  实例:

  ?

1 2 3 4 5 6 7 8 9 10 11 12 #!/usr/bin/ruby   x=1 if x > 2 puts "x is greater than 2" elsif x <= 2 and x!=0 puts "x is 1" else puts "I can't guess the number" end   x is 1

  Ruby if 修辞符:

  语法:

  code if condition

  if条件为真执行代码。

  实例:

  ?

1 2 3 4 #!/usr/bin/ruby   $debug=1 print "debugn" if $debug

  这将产生以下结果:

  ?

1 debug

  Ruby unless 语句:

  语法:

  ?

1 2 3 4 5 unless conditional [then] code [else code ] end

  如果条件为false,执行代码。如果条件是false,else子句中指定的代码被执行。

  例如:

  ?

1 2 3 4 5 6 7 8 #!/usr/bin/ruby   x=1 unless x>2 puts "x is less than 2" else puts "x is greater than 2" end

  这将产生以下结果:

  ?

1 x is less than 2

  Ruby unless 修辞符:

  语法:

  code unless conditional

  执行代码,如果有条件的话为false。

  实例:

  ?

1 2 3 4 5 6 7 8 #!/usr/bin/ruby   $var = 1 print "1 -- Value is setn" if $var print "2 -- Value is setn" unless $var   $var = false print "3 -- Value is setn" unless $var

  这将产生以下结果:

  ?

1 2 1 -- Value is set 3 -- Value is set

  Ruby case 语句

  语法:

  ?

1 2 3 4 5 6 case expression [when expression [, expression ...] [then] code ]... [else code ] end

  比较表达式指定的情况下,使用===运算符时,按指定的条款相匹配时执行的代码。

  子句计算 when 与左操作数指定的表达式。如果没有子句匹配时,情况下执行的代码else子句。

  when 语句的表达保留字,那么,一个换行符或分号分开代码。

  那么:

  ?

1 2 3 4 5 6 7 8 case expr0 when expr1, expr2 stmt1 when expr3, expr4 stmt2 else stmt3 end

  基本上类似于以下内容:

  ?

1 2 3 4 5 6 7 8 _tmp = expr0 if expr1 === _tmp || expr2 === _tmp stmt1 elsif expr3 === _tmp || expr4 === _tmp stmt2 else stmt3 end

  实例:

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #!/usr/bin/ruby   $age = 5 case $age when 0 .. 2 puts "baby" when 3 .. 6 puts "little child" when 7 .. 12 puts "child" when 13 .. 18 puts "youth" else puts "adult" end

  这将产生以下结果:

  ?

1 little child