Ruby 中 !! 的含义是什么?

4
在下面的方法中,!! 表示什么意思?
def include?(record)
  !!@association.include?(record)
end

它被称为双感叹号(!!)。 - Sharvy Ahmed
1
!!将“真值”(除了nilfalse之外的所有值)转换为true,并将“假值”(nilfalse)转换为false!!x意思是!(!x)。如果x是真值,则!xfalse;如果x是假值,则!xtrue。第一个!false翻转为true,将true翻转为false。例如,!!7 => !(!7) => !false => true!!nil => !(!nil) => !true => false - Cary Swoveland
你已经删除了最近的问题,请看看这里 ;) https://jsfiddle.net/m9gmjc2w/ - user4227915
3个回答

5

它将变量转换为布尔类型并确定其真值或假值

例如:

# Numbers...
!!1 # => true
!!0 # => true

# Numbers as strings...
!!'1' # => true
!!'0' # => false

# Truthy strings (case insensitive)...
!!'true'  # => true  (alias: 't')
!!'false' # => false (alias: 'f')
!!'yes'   # => false (alias: 'y')
!!'no'    # => false (alias: 'n')

# Booleans...
!!true  # => true
!!false # => false

# Nil...
!!nil # => false


3

它可以帮助您获得布尔结果。

例如:

a = nil
!a
#=> true
!!a
#=> false

同样地

a = 1
!a
#=> false
!!a
#=> true

0
双感叹号将结果转换为布尔值,因此在这种情况下,如果@assication.include?(record)返回nil,那么它将被转换为false

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接