ruby nil
true
, false
, and nil
are special built-in data types in Ruby. Each of these keywords evaluates to an object that is the sole instance of its respective class.
true
, false
和nil
是Ruby中的特殊內置數據類型。 這些關鍵字中的每一個都求值為一個對象,該對象是其各自類的唯一實例。
true.class=> TrueClass
false.class=> FalseClass
nil.class=> NilClass
true
and false
are Ruby’s native boolean values. A boolean value is a value that can only be one of two possible values: true or not true. The object true
represents truth, while false
represents the opposite. You can assign variables to true
/ false
, pass them to methods, and generally use them as you would other objects (such as numbers, Strings, Arrays, Hashes).
true
和false
是Ruby的本地布爾值。 布爾值是只能是兩個可能值之一的值:true或not true。 對象true
代表真相,而false
代表相反。 您可以將變量分配給true
/ false
,將它們傳遞給方法,并通常像使用其他對象(例如數字,字符串,數組,哈希)一樣使用它們。
nil
is a special value that indicates the absence of a value – it is Ruby’s way of referring to “nothing”. An example of when you will encounter the nil
object is when you ask for something that doesn’t exist or cannot be found:
nil
是一個特殊的值,它指示不存在值–這是Ruby引用“ nothing”的方式。 當您遇到不存在或找不到的東西時,便是遇到nil
對象的一個??示例:
hats = ["beret", "sombrero", "beanie", "fez", "flatcap"]hats[0]=> "beret" # the hat at index 0
hats[2]=> "beanie" # the hat at index 2
hats[4]=> "flatcap" # the hat at index 4
hats[5]=> nil # there is no hat at index 5, index 5 holds nothing (nil)
Zero is not nothing (it’s a number, which is something). Likewise, empty strings, arrays, and hashes are not nothing (they are objects, which happen to be empty). You can call the method nil?
to check whether an object is nil.
零不是什么(它是一個數字,是個數字)。 同樣,空字符串,數組和哈希也不是什么(它們是對象,碰巧是空的)。 您可以調用方法nil?
檢查對象是否為零。
0.nil?=> false
"".nil?=> false
[].nil?=> false
{}.nil?=> false
nil.nil?=> true# from the example above
hats[5].nil?=> true
Every object in Ruby has a boolean value, meaning it is considered either true or false in a boolean context. Those considered true in this context are “truthy” and those considered false are “falsey.” In Ruby, only false
and nil
are “falsey,” everything else is “truthy.”
Ruby中的每個對象都有一個布爾值,這意味著在布爾上下文中它被視為true或false。 在這種情況下,被認為是正確的是“真實的”,被認為是錯誤的是“假的”。 在Ruby中, 只有 false
和nil
是“ falsey”,其他所有東西都是“ true”。
更多信息: (More Information:)
Learning Ruby: From Zero to Hero
學習Ruby:從零到英雄
Idiomatic Ruby: writing beautiful code
慣用的Ruby:編寫漂亮的代碼
How to Export a Database Table to CSV Using a Simple Ruby Script
如何使用簡單的Ruby腳本將數據庫表導出為CSV
翻譯自: https://www.freecodecamp.org/news/data-types-in-ruby-true-false-and-nil-explained-with-examples/
ruby nil