Ruby if-else語句

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

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

1. Ruby if語句

Ruby if語句測試條件。 如果conditiontrue,則執行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中,執行上面代碼,得到以下結果 -

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

F:\worksp\ruby>

2. Ruby if else語句

Ruby if else語句測試條件。 如果conditiontrue,則執行if語句,否則執行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中,執行上面代碼,得到以下結果 -

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則執行if語句,否則執行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中,執行上面代碼,得到以下結果 -

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值,然後執行一個語句。

語法:

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

示例代碼

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

將上面代碼保存到檔:ternary-statement.rb中,執行上面代碼,得到以下結果 -

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

F:\worksp\ruby>

上一篇: Ruby數據類型 下一篇: Ruby Case語句