What is the point of object.presence?

后端 未结 5 923
太阳男子
太阳男子 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 20:50

    I just used it in a useful way I found neat. My variable is a string, if it's the empty string i want nil, otherwise I want it converted to an integer.

     x.presence.try(&:to_i)
    
     "".presence.try(&:to_i) # => nil
     "22".presence.try(&:to_i) # => 22
    

提交回复
热议问题