Truthiness
All objects may be converted to booleans in Ruby
Section titled “All objects may be converted to booleans in Ruby”Use the double negation syntax to check for truthiness of values. All values correspond to a boolean, irrespective of their type.
irb(main):001:0> !!1234=> trueirb(main):002:0> !!"Hello, world!"(irb):2: warning: string literal in condition=> trueirb(main):003:0> !!true=> trueirb(main):005:0> !!{a:'b'}=> trueAll values except nil and false are truthy.
irb(main):006:0> !!nil=> falseirb(main):007:0> !!false=> falseTruthiness of a value can be used in if-else constructs
Section titled “Truthiness of a value can be used in if-else constructs”You do not need to use double negation in if-else statements.
if 'hello' puts 'hey!'else puts 'bye!'endThe above code prints ‘hey!’ on the screen.
Remarks
Section titled “Remarks”As a rule of thumb, avoid using double-negations in code. Rubocop says that double negations are unnecessarily complex and can often be replaced with something more readable.
Instead of writing
def user_exists? !!userenduse
def user_exists? !user.nil?end