What is the point of object.presence?

Here's the point:

''.presence
# => nil

so if params[:state] == '':

region = params[:state].presence || 'US'
# => 'US'
region = params[:state] || 'US'
# => ''

What's more, it works in similar way (that is, returns nil if object is 'empty') on every object that responds to empty? method, for example:

[].presence
# => nil

Here's the documentation, for reference:

http://api.rubyonrails.org/classes/Object.html#method-i-presence


presence is very useful when you want to return nil if object is not present and the object itself if the object is present. In other words you want a code that looks like this:

object.present? object : nil

Instead of the line above you can simply call object.presence and the method will do the work for you.


As another example, presence lets me present my favorite FizzBuzz solution:

puts 1.upto(100).map { |n| "#{'Fizz' if n%3==0}#{'Buzz' if n%5==0}".presence || n }