What is the point of object.presence?

后端 未结 5 918
太阳男子
太阳男子 2021-02-06 20:33

In the Rails docs, the example provided for the object.presence method is:

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


        
5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-06 21:01

    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

提交回复
热议问题