Ruby - 条件判断

Ruby - 条件判断 首页 / Ruby入门教程 / Ruby - 条件判断

Ruby提供了现代语言非常常见的条件结构。在这里,无涯教程将解释Ruby中所有可用的条件语句和修饰符。

Ruby if ... else 语句

if conditional [then]
   code...
[elsif conditional [then]
   code...]...
[else
   code...]
end

Ruby if ... else 示例

#!/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

如果条件为true,则执行 code 。

Ruby if 示例

#!/usr/bin/ruby

$debug=1
print "debug\n" if $debug

这将产生以下输出-

debug

Ruby unless 语句

unless conditional [then]
   code
[else
   code ]
end

如果 conditional 为false,则执行 code 。如果 conditional 为true,则执行else子句中指定的代码。

无涯教程网

Ruby unless 示例

#!/usr/bin/ruby

x=1 
unless x>=2
   puts "x is less than 2"
 else
   puts "x is greater than 2"
end

这将产生以下输出-

x is less than 2

Ruby unless 语句

code unless conditional

如果 conditional 为false,则执行 code 。

Ruby unless 示例

#!/usr/bin/ruby

$var= 1
print "1 -- Value is set\n" if $var
print "2 -- Value is set\n" unless $var

$var=false
print "3 -- Value is set\n" unless $var

这将产生以下输出-

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

Ruby case 语句

case expression
[when expression [, expression ...] [then]
   code ]...
[else
   code ]
end

比较case指定的表达式和使用===运算符时指定的表达式,并执行匹配的when子句的 code 。

链接:https://www.learnfk.comhttps://www.learnfk.com/ruby/ruby-if-else.html

来源:LearnFk无涯教程网

when子句指定的表达式被判断为左操作数。如果when子句不匹配,则 case 执行 else 子句的代码。

when 语句的表达式与代码之间用保留字,换行符或分号隔开。因此-

case expr0
when expr1, expr2
   stmt1
when expr3, expr4
   stmt2
else
   stmt3
end

基本上类似于以下内容-

_tmp=expr0
if expr1 === _tmp || expr2 === _tmp
   stmt1
elsif expr3 === _tmp || expr4 === _tmp
   stmt2
else
   stmt3
end

Ruby case 示例

#!/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

这将产生以下输出-

little child

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

Go语言从入门到实战 -〔蔡超〕

Vue开发实战 -〔唐金州〕

后端技术面试 38 讲 -〔李智慧〕

跟月影学可视化 -〔月影〕

分布式数据库30讲 -〔王磊〕

HarmonyOS快速入门与实战 -〔QCon+案例研习社〕

React Native 新架构实战课 -〔蒋宏伟〕

B端体验设计入门课 -〔林远宏(汤圆)〕

互联网人的数字化企业生存指南 -〔沈欣〕

好记忆不如烂笔头。留下您的足迹吧 :)