"||" equivalent for .blank?

Hi all

Is there an equivalent to the || thing?

var = nil || "blah"
# => "blah"

var = "" || "blah"
# => ""

I want something like that:

var = nil ||| "blah"
# => "blah"

var = "" ||| "blah"
# => "blah"

Is there something like that in Rails? :slight_smile:

Thanks
Josh

To my knowledge, there is not.

var = "blah" if var.blank?

will however do what you want

This is logically equivalent, though not as pretty

   var = a.blank? ? b : a

Xavier Noria wrote:

In Ruby some "operators" are syntactic sugar for methods, for example
"<<", or "+". But there's no way to go in the other direction. That
is, you cannot define a method in Object named "|||" and tell Ruby it
should be parsed as an operator of such and such arity, etc.

Xavier Noria wrote:

Of course if a method is good for you this is doable

    class Object
      def bor(other)
        blank? ? other : self
      end
    end

    nil.bor("blah") # => "blah"
    ''.bor({}).bor("blah") # => "blah"
    [].bor("blah").bor(true) # => "blah"

Hi all

Is there an equivalent to the || thing?

var = nil || "blah"
# => "blah"

var = "" || "blah"
# => ""

I want something like that:

var = nil ||| "blah"
# => "blah"

var = "" ||| "blah"
# => "blah"

Is there something like that in Rails? :slight_smile:

Thanks
Josh

Like the Numeric#nonzero? that is useful in chained comparisons, you can define nonblank? to be similar and get this effect:

class String
   # Allowing a chain like: string_value.nonblank? || 'default value'
   def nonblank?
     self unless blank?
   end
end

class NilClass
   # Allowing a chain like: value.nonblank? || 'default value'
   def nonblank?
     self
   end
   # so it plays nicely with Numeric#nonzero?
   def nonzero?
     self
   end
end

Since you're already Rails, you're already ActiveSupport and blank? will be well defined.

nil.nonblank? || "blah"

=> "blah"

"".nonblank? || "blah"

=> "blah"

"foo".nonblank? || "blah"

=> "foo"

-Rob

Rob Biedenharn http://agileconsultingllc.com
Rob@AgileConsultingLLC.com

Thanks guys, I just found the blank? method. :slight_smile:

In Rails you can now do this:

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

http://apidock.com/rails/Object/presence