Coalesce (ruby method, not a SQL question)

51 views
Skip to first unread message

Daniel Loureiro

unread,
Mar 4, 2015, 10:32:02 AM3/4/15
to rubyonra...@googlegroups.com
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

Scott Ribe

unread,
Mar 4, 2015, 11:01:38 AM3/4/15
to rubyonra...@googlegroups.com
On Mar 4, 2015, at 8:32 AM, Daniel Loureiro <loure...@gmail.com> wrote:
>
> 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

a.presence || b

<http://api.rubyonrails.org/classes/Object.html#method-i-presence>

--
Scott Ribe
scott...@elevated-dev.com
http://www.elevated-dev.com/
(303) 722-0567 voice




Daniel Loureiro

unread,
Mar 4, 2015, 11:13:52 AM3/4/15
to rubyonra...@googlegroups.com
> > 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 

> a.presence || b 

Whoa! Thank you Scott, you save my day. 

--
Daniel Loureiro
Reply all
Reply to author
Forward
0 new messages