Ruby if else語句用于測試條件。 Ruby中有各種各樣的if語句。
if語句if-else語句if-else-if(elsif)語句Ruby if語句測試條件。 如果condition為true,則執(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í)行上面代碼,得到以下結(jié)果 -
F:\worksp\ruby>ruby if-statement.rb
90
You are eligible to vote.
F:\worksp\ruby>
Ruby if else語句測試條件。 如果condition為true,則執(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í)行上面代碼,得到以下結(jié)果 -
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>
Ruby if else if 語句測試條件。 如果condition為true則執(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í)行上面代碼,得到以下結(jié)果 -
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>
在Ruby三元語句中,if語句縮短。首先,它計算一個表達(dá)式的true或false值,然后執(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í)行上面代碼,得到以下結(jié)果 -
F:\worksp\ruby>ruby ternary-operator.rb
Ternary operator
5
2
F:\worksp\ruby>