Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby's Object#define_method vs Module#define_method

Tags:

ruby

Can anyone elaborate on the differences between ruby's Object#define_method and Module#define_method and where they are generally used?

like image 334
Pratik Khadloya Avatar asked May 21 '11 19:05

Pratik Khadloya


2 Answers

Object#define_method does not exist:

o = Object.new
o.define_method
#NoMethodError: undefined method `define_method' for #<Object:0x1448a80>

However, Object.define_method exists:

Object.define_method
#NoMethodError: private method `define_method' called for Object:Class

That's because Object is an object of class Class, and Class is a subclass of Module:

Object.class # => Class
Class.ancestors # => [Class, Module, Object, Kernel, BasicObject]

So when you call Object.define_method, you're calling Module#define_method.

Just remember that classes are objects of class Class, and it'll be as clear as mud!

like image 191
Andrew Grimm Avatar answered Nov 15 '22 11:11

Andrew Grimm


Object#define_method is actually Module#define_method.

pry(main)> Object.method(:define_method).owner
=> Module
pry(main)> Module.method(:define_method).owner
=> Module
like image 42
Dogbert Avatar answered Nov 15 '22 09:11

Dogbert