1

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?

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.