Ruby on Rails Wednesday, March 4, 2015

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
http://www.learnwithdaniel.com

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/13008592-2e2d-42d7-8503-f84135c36b64%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment