Hi everyone,
it’s a silly question (and I’m kind of ashamed to ask it), but I frequently must do things like that:
a.present? ? a : b
``
or a real world example:
params[:user][:name].present? ? params[:user][:name] : “default name”
``
I think these are perfect cases to use a “coalesce” method. Something like:
a.coalesce(b)
params[:user][:name].coalesce(“default name”)
``
or on a non-OOP/non-chained syntax:
coalesce(a, b, c, …)
coalesce(params[:user][:name], “default name”)
``
This method saves me a lot of time, so I create it in virtually every project that I have:
application.rb
class Object def coalesce(arg) self.blank? ? arg : self end end
``
Ex.:
2.coalesce(1) => 2 nil.coalesce(1) => 1
``
The complete version that I use is that:
class Object def coalesce(obj, *args) args.unshift(obj) # “obj” is to force at least 1 argument args.unshift(self) if self.class != Object # non-chained use result = args.shift args.each do |arg| if result.blank? result = arg else break end end result end alias_method :clsc, :coalesce end
``
This complete version allows me to use with all these syntax:
coalesce(1, 2) coalesce(1, 2, 3) 1.coalesce(2) 1.coalesce(2, 3) clsc(1, 2)
``
My question is: there is a native “coalesce” method (or something similar) in Ruby or Rails? I’m afraid to reinventing the wheel.
PS: a || b is not a valid answer because “” || “x” returns “” (and the main use for this is with strings).
Thanks,
Daniel Loureiro