Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby one liner for method undefined or nil

Tags:

ruby

I was curious whether there is a shorter way to check whether a method is defined on an object, and if it is, check whether it is nil or not. I've tried:

if !obj.respond_to?(:meth) || obj.meth.nil?

But it looks very long and ugly.

like image 804
linkyndy Avatar asked Dec 19 '22 05:12

linkyndy


2 Answers

Quick and dirty but concise:

unless (obj.meth rescue nil)
  ...
end

If sending meth to obj fails (e.g. because the method is missing), the expression takes the value nil.

Of course this hides all kinds of errors in meth.

like image 186
undur_gongor Avatar answered Jan 08 '23 04:01

undur_gongor


As @Sergio suggested, try from ActiveSupport is exactly what you want. Using try, your code would read like this:

if obj.try(:meth).nil?
  # obj either lacks :meth or has :meth that returns nil
end

Very concise and readable, I think.

If you aren't using ActiveSupport, you can quickly reimplement a simple version try yourself:

class Object
  def try(method, *args)
    public_send(method, *args) if respond_to?(method)
  end
end
like image 24
Matt Brictson Avatar answered Jan 08 '23 03:01

Matt Brictson