我是 Ruby 新手,遇到了defined?操作员。我认为?暗示该方法返回true/false但defined?如果已定义则返回标识符的描述。
我知道有一个true/false组件,其中标识符已定义或未定义,但我认为这?意味着返回值始终必须是true/false`。帮助?
我是 Ruby 新手,遇到了defined?操作员。我认为?暗示该方法返回true/false但defined?如果已定义则返回标识符的描述。
我知道有一个true/false组件,其中标识符已定义或未定义,但我认为这?意味着返回值始终必须是true/false`。帮助?
它返回一个“truthy”值,即“truthy-true”或“truthy-false”。
在 Ruby 中,只有两件事是真假:
false(单例对象)nil(单例对象)其他任何事情都被认为是真实的。大量的 Ruby 代码利用这一事实进行谓词。因此,对谓词的检查应该是:
if list.empty?
不是:
if list.empty? == true
defined? a #=> nil
a = 7 # => 7
defined? a #=> "local-variable"
虽然它不会传回实际的“真”或“假”值,但它仍然以相同的方式运行。
if defined? a
puts "This will still act as true"
end
#=> This will still act as true
The reason for this is because in ruby EVERYTHING is true with the exception of false and nil.
This link has a lot more information on the defined? operator.
这只是一个约定,而不是语言的一部分,因此没有围绕问号的实际规则。来自http://www.ruby-lang.org/en/documentation/ruby-from-other-languages/
“按照惯例,回答问题的方法(即 Array#empty? 如果接收方为空则返回 true)以问号结尾。”
"non-nil"/nil 与 Ruby 中的 true/false 相同。如果你来自其他语言,你可能有这种使用 true/false 进行测试的习惯,但是在 Ruby 中,我们会测试一个对象是否为 nil。
所以这两个是一样的:
a = 'hello'
if defined?(a) then puts a end
a = 'hello'
if defined?(a) != nil then puts a end
如果您坚持要返回 true/false,则可以使用第二个。这将返回真/假:
a != nil
The defined? operator returns nil if its argument (which can be an arbitrary expression) is not defined, otherwise it returns a description of that argument.
And since nil evaluates to false and (except for false) all other expressions evaluate to true, the behaviour of defined? is as one expects.