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.

truefalsenil是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).

truefalse是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中, 只有 falsenil是“ falsey”,其他所有东西都是“ true”。

更多信息: (More Information:)

翻译自: https://www.freecodecamp.org/news/data-types-in-ruby-true-false-and-nil-explained-with-examples/

ruby nil

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值