text
stringlengths
0
444
x = (not something)
# good
x = !something
----
=== Double Negation [[no-bang-bang]]
Avoid unnecessary uses of `!!`
`!!` converts a value to boolean, but you don't need this explicit conversion in the condition of a control expression; using it only obscures your intention.
Consider using it only when there is a valid reason to restrict the result `true` or `false`. Examples include outputting to a particular format or API like JSON, or as the return value of a `predicate?` method. In these cases, also consider doing a nil check instead: `!something.nil?`.
[source,ruby]
----
# bad
x = 'test'
# obscure nil check
if !!x
# body omitted
end
# good
x = 'test'
if x
# body omitted
end
# good
def named?
!name.nil?
end
# good
def banned?
!!banned_until&.future?
end
----
=== `and`/`or` [[no-and-or-or]] [[and-or-flow]]
Do not use `and` and `or` in boolean context - `and` and `or` are control flow
operators and should be used as such. They have very low precedence, and can be
used as a short form of specifying flow sequences like "evaluate expression 1,
and only if it is not successful (returned `nil`), evaluate expression 2". This
is especially useful for raising errors or early return without breaking the
reading flow.
[source,ruby]
----
# good: and/or for control flow
x = extract_arguments or raise ArgumentError, "Not enough arguments!"
user.suspended? and return :denied
# bad
# and/or in conditions (their precedence is low, might produce unexpected result)
if got_needed_arguments and arguments_valid
# ...body omitted
end
# in logical expression calculation
ok = got_needed_arguments and arguments_valid
# good
# &&/|| in conditions
if got_needed_arguments && arguments_valid
# ...body omitted
end
# in logical expression calculation
ok = got_needed_arguments && arguments_valid
# bad
# &&/|| for control flow (can lead to very surprising results)
x = extract_arguments || raise(ArgumentError, "Not enough arguments!")
----
Avoid several control flow operators in one expression, as that quickly
becomes confusing:
[source,ruby]
----
# bad
# Did author mean conditional return because `#log` could result in `nil`?
# ...or was it just to have a smart one-liner?
x = extract_arguments and log("extracted") and return
# good
# If the intention was conditional return
x = extract_arguments
if x
return if log("extracted")
end
# If the intention was just "log, then return"
x = extract_arguments
if x
log("extracted")
return
end
----