Friday, July 12, 2013

[ruby] Calling :methods on BasicObject


So, I just learnt a couple of days ago that you could pass in false to  :methods , and it'll filters out the inherited methods and return an array of only the methods that are defined in the class.
And as I spent time playing with it, I thought I'll check how BasicObject would respond to, if I called methods(false) on it.

My assumption was that BasicObject would possibly be the only class which would return back the same array for :methods(true) and :methods(false) - since it doesn't inherit from anything.

So here's what I did

BasicObject.methods(false) # => []

An empty array? Given that BasicObject is the root of Ruby's object hierarchy, it didn't make sense that BasicObject could respond differently for :methods(true) and :methods(false) - So where were those methods coming from?

After a few mins of trying to Google, I reached out to [Chew Choon Keat](http://blog.choonkeat.com/) and he figured the obvious problem here. It wasn't BasicObject responding to the call - The receiver was instead a Class object.

:instance_methods seems to be respond like how I expected it to though.

Oh, and :methods is defined in the Kernel module, that gets included into Object class.

#TIL
Post a Comment