ruby ,!!运算符(a/k/a 双爆炸)

标签 ruby operators

<分区>

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/

相关文章:

ruby - 使用 byebug 调试时如何缩放堆栈?

mysql - 我可以按预定顺序加载 ActiveRecord-Objects 吗?

ruby - 如何测试文件操作

Python + 和 * 运算符

PostgreSQL 错误 : operator >> is not a valid ordering operator

perl - yada-yada 运算符是否已被弃用?

ruby - 如何最好地包装 Ruby optparse 代码和输出?

ruby - gem 在 MAC 10.7.5 上安装 pg?

c - C语言中的短路评估是什么?

C: 如果 x 是 char 类型,在 x=~x 中会发生什么(详细)?