0

I know how to use include to add mixins to a class in Ruby. However, I want to add one or more methods to an already instantiated object. Is that possible?

For example, the Rack::File::Iterator class behaves as an iterator, but it doesn't inherit from Enumerable. This means that it doesn't come with a reduce method, even though it does contain an each method.

I'd like to add the reduce method to an already-instantiated Rack::File::Iterator object (which I'll refer to as "obj" here), so that I can just do the following ...

result = obj.reduce { |a,b| a + b }

If I could somehow include the Enumerable module into the already-instantiated obj, I think this would accomplish what I want.

I am only referring to Rack::File::Iterator as an example. I'm looking for a general solution which will work with instantiated objects of any class. Furthermore, I'm only using reduce as an example, as well. I want this to work with any methods I might wish to add to an object.

Yes, I know how to write my own reduce function to which I could pass obj and a block as parameters. However, I'd prefer to do this kind of dynamic include into an already-instantiated object, if possble.

Thank you in advance.

ADDENDUM

I went to the article referenced below (thank you!), and I then realized that there is yet another way to do this which was not mentioned in that article. Therefore, I added another answer to that article with the methodology that I thought of. Here it is, using the example I outlined above ...

class << obj
  include Enumerable  # or any other module
end

This adds all the methods from Enumerable into my object.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
HippoMan
  • 2,119
  • 2
  • 25
  • 48

1 Answers1

0

Yeah, it is possible.

Add method to an instanced object

TedTran2019
  • 887
  • 5
  • 15