Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good idea to use method_missing on nil in ruby

Tags:

ruby

In ruby I'm tired of constantly checking if an object has all necessary properties and sub-properties before using them like

if (obj && obj[:a] && obj[:a][:b] && obj[:a][:b][:c] && obj[:a][:b][:c] > 0)
    # do something useful
end

Is it a good idea to avoid this by defining method_missing on NilClass to return nil?

class NilClass
    def method_missing(method_name, *args, &block)
        nil
    end
end

This way with properly written comparisons I can use default values to handle everything.
I can even compare to other expressions like

if (obj[:a][:b][:c] > 0)
    # do something useful
else
    # default behaviour if obj[:a][:b][:c] <= 0 or obj[:a][:b][:c] is undefined
end

In exceptional cases I can always manually check for nil.

What can get broken?

like image 784
xaxa Avatar asked Nov 27 '25 21:11

xaxa


1 Answers

Using Hash.fetch would allow you to return false if it doesn't exist and short circuit that conditional. http://ruby-doc.org/core-1.9.3/Hash.html#method-i-fetch

if obj.fetch(:a, {}).fetch(:b, {}).fetch(:c, false)
  #useful stuff
end

And as was mentioned in the comments if you really didn't want to check if this object was a hash not you could do (obj||{}).fetch(:a, {}).fetch(:b, {}).fetch(:c, false)

like image 172
Jared Avatar answered Nov 29 '25 16:11

Jared



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!