Reputation: 30206
I see how to dynamically add a method to an instance in Ruby with def [instance].[methodname]; [...]; end
.
However, I'm interested in attaching a method that exists in another location to a given instance. e.g.
def my_meth
puts self.foo
end
class MyCls
attr_accessor :foo
end
my_obj = MyCls.new
my_obj.my_meth
How could I simply attach my_meth
to my_obj
so that the method call in the final line of the foregoing code would work?
Upvotes: 1
Views: 829
Reputation:
You could use include
or extend
to add a module to your class, eg. extend
:
module Foo
def my_meth
puts self.foo
end
end
class MyCls
attr_accessor :foo
end
my_obj = MyCls.new
my_obj.extend(Foo)
my_obj.foo = "hello"
my_obj.my_meth
Unless you have a need to mix-in a module on the fly like this it's generally better to include
your module like so:
class MyCls
include Foo
attr_accessor :foo
end
Upvotes: 6