The Spaghetti Refactory Established 2015

present? vs any? in Rails

First, a few definitions, direct from the Ruby docs  and Rails docs:

An object is present if it’s not blank?

An object is blank if it’s false, empty, or a whitespace string.

Passes each element of the collection to the given block. The method returns true if the block ever returns a value other than false or nil. If the block is not given, Ruby adds an implicit block of { |obj| obj } that will cause any? to return true if at least one of the collection members is not false or nil. 

present? is a Rails method from ActiveSupport
any? is pure Ruby A few important points:

# => NoMethodError: undefined method `any?' for nil:NilClass

# => false

[""].any? && [""].present?
# => true

[""].any? &:present?
# => false

The last example is good if you need to make sure there are no blank values in an array.

 So, how do all of these measure up, performance-wise? Well, they're all pretty similar, but it seems that any? is moderately faster than present, so if you can get away with it, go for that one. However, as far as I'm concerned, when dealing with such a small performance difference, readability becomes more important, so I would personally go for whichever is more readable that still accomplishes my purposes. With arrays, that tends to be any? most of the time.


array = (0..500000).to_a
Benchmark.bmbm do |x|"any with empty array:") { 100000.times { [].any? } }"present with empty array:") { 100000.times { [].present? } }"any with stuff:") { 100000.times { array.any? } }"present with stuff:") { 100000.times { array.present? } }

user system total real
any with empty array: 0.010000 0.000000 0.010000 ( 0.010986)
present with empty array: 0.010000 0.000000 0.010000 ( 0.015146)
any with stuff: 0.010000 0.000000 0.010000 ( 0.008500)
present with stuff: 0.010000 0.000000 0.010000 ( 0.012448)