From: Florian Gross Date: 2004-11-16T06:18:24+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? IMHO it is currently the above for very special methods and core class additions for more general methods. In Ruby2 there will be namespace selectors which will let you localize changes to core classes. IIRC David Black already implemented something similar for current Ruby, but I'm not sure if it is thread safe.