鍍金池/ 教程/ Ruby/ Ruby if-else語句
Ruby for循環(huán)
Ruby教程
Ruby文件I/O
Ruby迭代器
Ruby哈希
Ruby日期時間
Ruby類和對象
Ruby快速入門(30分鐘)
Ruby redo/retry語句
Ruby模塊
Ruby解析XML(REXML)
Ruby if-else語句
Ruby的功能特點
Ruby break/next語句
Ruby方法
Ruby是什么?
Ruby與Python比較
Ruby Case語句
Ruby目錄
Ruby范圍
Ruby異常
Ruby套接字編程(Socket)
Ruby字符串
Ruby安裝配置
Ruby運算符
Ruby while/do...while循環(huán)語句
Ruby第一個HelloWorld程序
Ruby until循環(huán)語句
Ruby注釋
Ruby塊
Ruby數據類型
Ruby面向對象
Ruby正則表達式
Ruby數組
Ruby變量
Ruby多線程編程

Ruby if-else語句

Ruby if else語句用于測試條件。 Ruby中有各種各樣的if語句。

  • if語句
  • if-else語句
  • if-else-if(elsif)語句
  • 三元(縮寫if語句)語句

1. Ruby if語句

Ruby if語句測試條件。 如果conditiontrue,則執(zhí)行if語句。

語法:

if (condition)  
//code to be executed  
end

流程示意圖如下所示 -

代碼示例:

a = gets.chomp.to_i   
if a >= 18   
  puts "You are eligible to vote."   
end

將上面代碼保存到文件:if-statement.rb中,執(zhí)行上面代碼,得到以下結果 -

F:\worksp\ruby>ruby if-statement.rb
90
You are eligible to vote.

F:\worksp\ruby>

2. Ruby if else語句

Ruby if else語句測試條件。 如果conditiontrue,則執(zhí)行if語句,否則執(zhí)行block語句。

語法:

if(condition)  
    //code if condition is true  
else  
//code if condition is false  
end

流程示意圖如下所示 -

代碼示例:

a = gets.chomp.to_i   
if a >= 18   
  puts "You are eligible to vote."   
else   
  puts "You are not eligible to vote."   
end

將上面代碼保存到文件:if-else-statement.rb中,執(zhí)行上面代碼,得到以下結果 -

F:\worksp\ruby>ruby if-else-statement.rb
80
You are eligible to vote.

F:\worksp\ruby>ruby if-else-statement.rb
15
You are not eligible to vote.

F:\worksp\ruby>

3. Ruby if else if(elsif)

Ruby if else if 語句測試條件。 如果conditiontrue則執(zhí)行if語句,否則執(zhí)行block語句。

語法:

if(condition1)  
//code to be executed if condition1is true  
elsif (condition2)  
//code to be executed if condition2 is true  
else (condition3)  
//code to be executed if condition3 is true  
end

流程示意圖如下所示 -

示例代碼 -

a = gets.chomp.to_i   
if a <50   
  puts "Student is fail"   
elsif a >= 50 && a <= 60   
  puts "Student gets D grade"   
elsif a >= 70 && a <= 80   
  puts "Student gets B grade"   
elsif a >= 80 && a <= 90   
  puts "Student gets A grade"    
elsif a >= 90 && a <= 100   
  puts "Student gets A+ grade"    
end

將上面代碼保存到文件:if-else-if-statement.rb中,執(zhí)行上面代碼,得到以下結果 -

F:\worksp\ruby>ruby if-else-if-statement.rb
25
Student is fail

F:\worksp\ruby>ruby if-else-if-statement.rb
80
Student gets B grade

F:\worksp\ruby>

4. Ruby三元語句

在Ruby三元語句中,if語句縮短。首先,它計算一個表達式的truefalse值,然后執(zhí)行一個語句。

語法:

test-expression ? if-true-expression : if-false-expression

示例代碼

var = gets.chomp.to_i;   
a = (var > 3 ? true : false);    
puts a

將上面代碼保存到文件:ternary-statement.rb中,執(zhí)行上面代碼,得到以下結果 -

F:\worksp\ruby>ruby ternary-operator.rb
Ternary operator
5
2

F:\worksp\ruby>

上一篇:Ruby模塊下一篇:Ruby異常