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.
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With