Using send to define object methods

Hello

If I want to add a method to a class, I can use send as shown below. Is
there a similar way to use send to add a method to an object?

class MyClass
end

MyClass.send(:define_method, :poof) {‘I say poof!’}

x = MyClass.new
x.poof # => “I say poof!”

I can define an object method as follows:

def x.object_poof
‘I say object_poof’
end

x.object_poof # => “I say object_poof”

I would like to use send to define object methods but I have not figured
out how.

Thanks
Dave Miller

Hello,

If you execute your script on Ruby 1.9, you can use
Object#define_singleton_method to add a method to an object.

— begin: example —

class MyClass
end
MyClass.send(:define_method, :poof) {‘I say poof!’}
x = MyClass.new
y = MyClass.new

x.define_singleton_method( :poof_singleton ) { “Here is in a singleton
method.” }
x.poof_singleton #=> “Here is in a singleton method.”
y.poof_singleton #=> NoMethodError

— end: example —

The method Object#define_singleton_method is able to be used on Ruby
1.9, but I couldn’t find out its doc…

2010/9/18 David M. [email protected]:

David M. wrote:

I would like to use send to define object methods but I have not figured
out how.

There is a magic incantation to get at the singleton class:

object_poof = Object.new
class <<object_poof; self; end.send(:define_method, :poof) {‘I say
poof!’}
object_poof.poof

I would personally use .class_eval { define_method … } instead of
.send(:define_method …) but that’s just preference.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs