最基本的當然就是 && (and) 與 || (or)兩種
一般來說最常與布林值 true 與 false 並用
在高中數學開始之前其實都會有一堂邏輯的基本概論,最常聽到的比喻說法是:
and 看作是乘法or 看作是加法其中 false 當作 0,而 true 即為任何一個 非0 的數(最常用 1 來舉例)
於是就會有下表(即最基本的真值表):
| 邏輯運算 | 結果 | 想成 | 
|---|---|---|
| True and True | True | 1 * 1 = 1 | 
| True and False | False | 1 * 0 = 0 | 
| False and False | False | 0 * 0 = 0 | 
| False and True | False | 0 * 1 = 0 | 
| True or True | True | 1 + 1 = 2 | 
| True or False | True | 1 + 0 = 1 | 
| False or False | False | 0 + 0 = 0 | 
| False or True | True | 0 + 1 = 1 | 
但在程式語言中,邏輯運算子並不是只能回傳布林值,而是幫我們做了一個很方便的簡化,將非布林值先轉化成布林值運算,再將結果轉化為原值回傳。那麼到底實際運作是如何呢?簡單來說就是尋找最短取值路徑。
首先我們先來看 and:
true 時:結果會跟第二個值相同,所以這時只要直接回傳第二個值就好,電腦本身並不在意第二個值是 true 還是 false 。false 時:則直接回傳第一個值。1 && "cat"    # 回傳 "cat"
nil && "dog"  # 回傳 "nil"
同理可證 or 的規則:
True 時,就直接回傳其值。False 時,回傳第二個值。1 || "cat"    # 回傳 1
nil || "dog"  # 回傳 "dog"
那我們可以利用上面的規則做什麼呢?舉例來說,可以拿來當作預設值的設定,學習程式基本上就是噴錯再修正的循環歷程,而預設值可以大幅的減少錯誤發生,也是一種未雨綢繆的表現,還記得我們第五天 - Hash篇的自我介紹嗎?我們可以幫它加上尷尬卻又不失禮貌的預設值:
class Introduction
  def initialize(profile = {})
    @name = profile[:name] ||"人見人愛小天才"
    @age = profile[:age] || "仍然是永遠的18歲"
    @email = profile[:email] || "傳小紙條的方式"
    @city = profile[:city] || "地球"
    @language = profile[:language] || "各種各樣有趣的事"
  end
  def say
    puts "我的名字是:#{@name},年紀:#{@age},可以用#{@email}聯絡我,標準#{@city}人,正在學習#{@language},請多指教! "
  end
end
Karen = Introduction.new
Karen.say
# 印出以下內容
# 我的名字是:人見人愛小天才,年紀:仍然是永遠的18歲,可以用傳小紙條的方式聯絡我,標準地球人,正在學習各種各樣有趣的事,請多指教!
如此以來一時緊張忘記給幾個條件也不會噴錯,但是 initialize 後面是要帶參數的,這裡給他一個空的 hash ,關於 class 的部分,在未來的幾天會有介紹。
此文同步刊登於CJ-Han的網站