From: Joel VanderWerf Date: 2004-11-16T07:18:08+09:00 Subject: Re: "The Ruby Way" and adding methods to base classes in libraries Moses Hohman wrote: > I have a question about practical experience with adding methods to base > classes in libraries. Say I'm writing a library and in a method of that > library, I need a method like "first_superset_of", which acts on an > array of arrays, and returns the first such array that is a superset of > a second array argument's elements, i.e. > > def first_superset_of(arrays, elements) > arrays.detect do |array| > elements.detect do |element| > not array.include?(element) ? false : true > end > end > end > private :first_superset_of > > Now, it's not very object-oriented to add this as a private method in a > class that is not an array or an enumerable or whatever and then call it > on two arguments. It seems more the ruby way to actually add a method > called first_superset_of (and maybe a method called subset_of? for the > second inner loop in there) to Enumerable or to Array, and then use that > method that way. However, adding this method might clash with another > added method in another library that a user might be using, if the > author of that other library also created a method on Array or > Enumerable with the same name. > > So, what's the right way to handle this situation? You could define this method in a module and use Object#extend to give that functionality to particular arrays. It doesn't completely prevent conflicts, but it does limit the instances that might be affected.