class RuboCop::Cop::Style::DoubleNegation
this is rarely a problem in practice.
As you’re unlikely to write code that can accept values of any type
!!something and !something.nil? are not the same thing.
Please, note that when something is a boolean value
end
!!return_value
def foo?
# bad
@example EnforcedStyle: forbidden
end
!!return_value
def foo?
# good
@example EnforcedStyle: allowed_in_returns (default)
!something.nil?
# good
!!something
# bad
@example
should be forbidden always.
that use boolean as a return value. When using ‘EnforcedStyle: forbidden`, double negation
When using `EnforcedStyle: allowed_in_returns`, allow double negation in contexts
This cop checks for uses of double negation (`!!`) to convert something to a boolean value.
def allowed_in_returns?(node)
def allowed_in_returns?(node) node.parent&.return_type? || end_of_method_definition?(node) end
def end_of_method_definition?(node)
def end_of_method_definition?(node) return false unless (def_node = find_def_node_from_ascendant(node)) last_child = def_node.child_nodes.last last_child.last_line == node.last_line end
def find_def_node_from_ascendant(node)
def find_def_node_from_ascendant(node) return unless (parent = node.parent) return parent if parent.def_type? || parent.defs_type? find_def_node_from_ascendant(node.parent) end
def on_send(node)
def on_send(node) return unless double_negative?(node) && node.prefix_bang? return if style == :allowed_in_returns && allowed_in_returns?(node) location = node.loc.selector add_offense(location) do |corrector| corrector.remove(location) corrector.insert_after(node, '.nil?') end end