<分区>
Possible Duplicate:
What does !! mean in ruby?
你好,
我是 Ruby 的新手,在任何地方都找不到“!!”的描述。方法。
这是一个例子:
def signed_in?
!!current_user
end
如果这是双重否定,为什么不说:
def signed_in?
current_user
end
请帮忙。
<分区>
Possible Duplicate:
What does !! mean in ruby?
你好,
我是 Ruby 的新手,在任何地方都找不到“!!”的描述。方法。
这是一个例子:
def signed_in?
!!current_user
end
如果这是双重否定,为什么不说:
def signed_in?
current_user
end
请帮忙。
最佳答案
在 Ruby(以及许多其他语言)中,有许多值在 bool 上下文中的计算结果为 true
,还有少数会计算为 false。在 ruby 中,the only two things that evaluate to false
are false
(itself) and nil
.
如果你否定某些东西,那会强制一个 bool 上下文。当然,它也否定它。如果你双重否定它,它会强制 bool 上下文,但会返回正确的 bool 值。
例如:
"hello" #-> this is a string; it is not in a boolean context
!"hello" #-> this is a string that is forced into a boolean
# context (true), and then negated (false)
!!"hello" #-> this is a string that is forced into a boolean
# context (true), and then negated (false), and then
# negated again (true)
!!nil #-> this is a false-y value that is forced into a boolean
# context (false), and then negated (true), and then
# negated again (false)
在您的示例中,signed_in?
方法应该返回一个 bool 值(按照惯例由 ?
字符表示)。它用于确定此值的内部逻辑是检查是否设置了 current_user
变量。如果已设置,它将在 bool 上下文中计算为 true
。如果不是,它将评估为 false。双重否定强制返回值为 bool 值。
关于 ruby ,!!运算符(a/k/a 双爆炸),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3994033/