有什么用!!ruby 是什么意思? [英] What does !! mean in ruby?
问题描述
只是想知道 !!
在 Ruby 中是什么.
Just wondering what !!
is in Ruby.
推荐答案
不是不是.它用于将值转换为布尔值:
Not not. It's used to convert a value to a boolean:
!!nil #=> false
!!"abc" #=> true
!!false #=> false
通常没有必要使用它,因为 Ruby 的唯一错误值是 nil
和 false
,所以通常最好让这个约定成立.
It's usually not necessary to use though since the only false values to Ruby are nil
and false
, so it's usually best to let that convention stand.
把它想象成
!(!some_val)
它合法使用的一件事是防止返回大量数据.例如,您可能不想在 has_image?
方法中返回 3MB 的图像数据,或者您可能不想在 logged_in?
方法中返回整个用户对象.使用 !!
将这些对象转换为简单的 true
/false
.
One thing that is it used for legitimately is preventing a huge chunk of data from being returned. For example you probably don't want to return 3MB of image data in your has_image?
method, or you may not want to return your entire user object in the logged_in?
method. Using !!
converts these objects to a simple true
/false
.
这篇关于有什么用!!ruby 是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!