Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby enumerables don't keep the same class

I have a class that represents a collection. I included the Enumerable module into it and defined the method #each, so that I get all its methods.

But the problem is that Enumerable's methods don't keep the same class. So, for example, if my class is named Collection, and if I do Collection#select, I would like that the result's class is also Collection (instead of Array). Is there a way how to achieve this?

like image 612
janko-m Avatar asked Oct 26 '12 23:10

janko-m


1 Answers

Since Enumerable#select is designed to return an array, you need to tell somewhere how to map that to a Collection instance. That means, you explicitly need to define Collection#select. Otherwise Ruby will not know the mapping rule from the original array result of Enumerable#select to a Collection instance.

like image 92
sawa Avatar answered Sep 27 '22 23:09

sawa