ruby nil_Ruby中的数据类型-True,False和Nil用示例解释
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中的特殊內(nèi)置數(shù)據(jù)類型。 這些關(guān)鍵字中的每一個(gè)都求值為一個(gè)對(duì)象,該對(duì)象是其各自類的唯一實(shí)例。
true.class=> TrueClass false.class=> FalseClass nil.class=> NilClasstrue 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的本地布爾值。 布爾值是只能是兩個(gè)可能值之一的值:true或not true。 對(duì)象true代表真相,而false代表相反。 您可以將變量分配給true / false ,將它們傳遞給方法,并通常像使用其他對(duì)象(例如數(shù)字,字符串,數(shù)組,哈希)一樣使用它們。
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是一個(gè)特殊的值,它指示不存在值–這是Ruby引用“ nothing”的方式。 當(dāng)您遇到不存在或找不到的東西時(shí),便是遇到nil對(duì)象的一個(gè)??示例:
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.
零不是什么(它是一個(gè)數(shù)字,是個(gè)數(shù)字)。 同樣,空字符串,數(shù)組和哈希也不是什么(它們是對(duì)象,碰巧是空的)。 您可以調(diào)用方法nil? 檢查對(duì)象是否為零。
0.nil?=> false "".nil?=> false [].nil?=> false {}.nil?=> false nil.nil?=> true# from the example above hats[5].nil?=> trueEvery 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中的每個(gè)對(duì)象都有一個(gè)布爾值,這意味著在布爾上下文中它被視為true或false。 在這種情況下,被認(rèn)為是正確的是“真實(shí)的”,被認(rèn)為是錯(cuò)誤的是“假的”。 在Ruby中, 只有 false和nil是“ falsey”,其他所有東西都是“ true”。
更多信息: (More Information:)
Learning Ruby: From Zero to Hero
學(xué)習(xí)Ruby:從零到英雄
Idiomatic Ruby: writing beautiful code
慣用的Ruby:編寫漂亮的代碼
How to Export a Database Table to CSV Using a Simple Ruby Script
如何使用簡(jiǎn)單的Ruby腳本將數(shù)據(jù)庫(kù)表導(dǎo)出為CSV
翻譯自: https://www.freecodecamp.org/news/data-types-in-ruby-true-false-and-nil-explained-with-examples/
ruby nil
總結(jié)
以上是生活随笔為你收集整理的ruby nil_Ruby中的数据类型-True,False和Nil用示例解释的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: ⚡如何在2分钟内将GraphQL服务器添
- 下一篇: 梦到媳妇回家了什么意思