跳至主要内容

[Ruby] 流程控制(control flow)與運算子(operator)

在 Ruby 裡因為所有的東西都是物件,在 Ruby 只有 nilfalse 會被當假的(false),除此這兩個之外,其它都是真的(true),包括數字 0、空陣列、空字串都是 true

控制結構(Control Structure)

if statement

# if condition
if a > b
# do something ...
elsif a > c
[do something]
else
[do something else ...]
end

# 把 if 放到後面: express if boolean
puts "你是大人了" if age >= 18

# 三元運算子: boolean ? Do this if true: Do this if false
title = (gender == 1) ? "先生" : "小姐"

unless statement

# 為了增加程式碼的可讀性,除了 if 之外,Ruby 還有提供 unless 語法可以用,unless 等於 if not 的效果,所以如果本來長得像這樣的:
unless age > 18 # 等於 if not age > 18
puts "kid"
end

puts "kid" unless age > 18

case statement

# 寫法一
case [variableName]
when "reverse"
# do something ...
when "uppercase"
# do something ...
when "both"
# do something ...
else
# do something ...
end

# 寫法二
case language
when "JS" then puts "Websites!"
when "Python" then puts "Science!"
when "Ruby" then puts "Web apps!"
else puts "I don't know!"
end

運算子(Operator)

Boolean/Logical Operators

可以使用符號(&&, ||, !)或文字(and, or, not),但符號有較高的優先權(precedence):

# boolean / logical operators
a && b # and
a and b

a || b # or
a or b

!a # not
not a

a <=> b # combined comparison operator,如果 a > b 回傳 1;a = b 回傳 0; a < b 回傳 -1
資訊

comparators / relational operators

# comparators / relational operators
a == b # Equal
a != b # Unequal
a < b # Less Than
a <= b # Less than or equal to
a > b
a >= b

conditional assignment operator

a ||= b        # a = a || b

參考資料