They don't do the same thing at all.
In Ruby everything except nil
and false
are truthy. This is amazingly sane compared to the type casting schenigans in other popular dynamic languages.
irb(main):003:0> !!""
(irb):3: warning: string literal in condition
=> true
irb(main):004:0> !!0
=> true
irb(main):005:0> !![]
=> true
irb(main):006:0> !!{}
=> true
irb(main):007:0> !!Object.new
=> true
irb(main):008:0> !!nil
=> false
irb(main):009:0> !!false
=> false
present?
and presence
are a part of ActiveSupport which can be used to test for nil and false but are actually more useful when dealing with user input:
irb(main):010:0> "".present?
=> false
irb(main):011:0> [].present?
=> false
irb(main):012:0> {}.present?
=> false
present?
and presence
are widely overused by Rails beginners that don't bother to learn Ruby first. Just use implicit truth checks (if foo
) or foo.nil?
if you just want to check if an argument is sent or not or if a variable is set.
And while .present?
can be used on ActiveRecord collections but there are more idiomatically correct choices such as any?
and none?
.