Ruby 程式設計中的 True、False 和 Nil
我們知道在 Ruby 中一切都被視為物件,包括 **true**、**false** 和 **nil**。它們是 Ruby 提供的內建型別,用於執行不同的條件檢查等操作。在本文中,我們將探討 **true**、**false** 和 **nil** 資料型別的不同示例以及如何使用它們。
Ruby 中的 True 和 False
讓我們從一個非常簡單的例子開始,我們將檢查兩個變數是否相等。
示例 1
請考慮以下程式碼
first = 10 second = 10 if first == second # If Condition is true puts "True! First and second are equal" else # If Condition is false puts "False! First and second are not equal" end
輸出
它將生成以下輸出:
True! First and second are equal
示例 2
讓我們再看一個 **True** 和 **False** 的例子。在這裡,我們將比較兩個字串。
a1 = "The quick brown fox jumps over the lazy dog." b1 = "The quick brown fox jumps over the lazy dog." result1 = a1 == b1 puts result1 a2 = "An apple a day keeps the doctor away." b2 = "An orange a day keeps the doctor away." result2 = a2 == b2 puts result2
輸出
它將生成以下輸出:
true false
Ruby 中的 Nil
現在我們已經瞭解瞭如何在 Ruby 中使用 **True** 和 **False** 內建型別,讓我們也探索一些 **Nil** 的程式碼示例。
示例 3
請考慮以下程式碼
arr = [ 1, 2, 3, 4, 5 ] # Since arr[5] does not exist, it is nil. res1 = arr[5].nil? puts res1 # Since arr[2] exists, it is not nil. res2 = arr[2].nil? puts res2
輸出
它將生成以下輸出:
true false
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP