On Thursday, July 5, 2012 5:52:22 AM UTC-4, Robert Klemme wrote: > > On Thu, Jul 5, 2012 at 11:41 AM, Soichi Ishida <[email protected]> > wrote: > > Hi. Could anyone help me understand the following? I am reading a > > piece of code that someone else wrote. > > > > > > class RegexAlternation < Array > > def sort > > self.clone.replace(super) > > end > > > > def uniq > > self.clone.replace(super) > > end > > > > def map > > self.clone.replace(super {|x| yield(x)}) > > end > > > > def delete_if > > self.clone.replace(super {|x| yield(x)}) > > end > > > > def select > > self.clone.replace(super {|x| yield(x)}) > > end > > end > > > > It looks like overriding the existing methods. But the definitions are > > very simple, so I am kinda lost here. > > > > I appreciate if you provide some test codes to see what they do. > > These super class methods will return Array instances but the author > wanted to make sure they return instances of RegexAlternation in class > RegexAlternation. > > Few remarks: "self." is superfluous. "clone" should be replaced by > "dup" because otherwise methods will break on a frozen instance. > > Generally it's a bad idea IMHO to inherit core classes. For example, > someone testing for Array will receive true and might be tempted to do > things with the instance which do not make sense for a > RegexAlternation. It's better to create a completely unrelated class > which can still implement the same API (or part of it) as the wrapped > class if necessary. >
I'm actually slightly surprised that it doesn't return a new instance of the subclass without such modifications. B/c you are right. Things like this do severely limit the utility of subclassing. Seems to me, the OOP ideals of inheritance never really worked out. Maybe things are different in Javaland, but you would think, inheritance really lived up to it's purpose, there would be large libraries of reusable class systems. Perhaps there are other reasons, but we never see such things. In Rubyland, it seems the only thing inheritance is good for is the creation of a base class for adapters, and even that could be managed via mixins if necessary. Sometimes I wonder if we could do just as well toss out inheritance altogether and simply provide more convenient and efficient support for delegation. -- You received this message because you are subscribed to the Google Groups ruby-talk-google group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at https://groups.google.com/d/forum/ruby-talk-google?hl=en
