M
Moses Hohman
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?
thanks in advance for any comments,
Moses
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?
thanks in advance for any comments,
Moses