ruby-on-railsruby

What is the point of Object#presence in Rails?


In the Rails docs, the example provided for the Object#presence method is:

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

But isn't that just equivalent to:

region = params[:state] || params[:country] || 'US'

What is the point of using presence?


Solution

  • 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