David A. Black wrote: > > module ExtendedSlicer > def slice(*args) > arg0 = args[0] > case arg0 > when Regexp > grep(arg0) > else > super > end > end > end > > a = %w{ one two three four }.extend(ExtendedSlicer) > a.slice(0,2) # ["one", "two"] > a.slice(/o/) # ["one", "two", "four"] > > The main advantage here is that it's a better fit: you need an object to > behave a certain way, and you teach that object to behave that way. > Another advantage is that it makes you work a little harder, and > therefore helps you evaluate more carefully whether or not you need to > perform the modification at all. > Ok, I've learned more from these posts than in two months of experiments. Said that "is a bad idea to override a built-in method", I'm trying to think in this way now: "what happens if I...", so I tried this: class MyArray < Array; end module ExtendedSlicer def slice(*args) arg0 = args[0] case arg0 when Regexp grep(arg0) else super end end end class MyArray include ExtendedSlicer end arr = MyArray.new %w{a b c ab} puts arr.slice(/a/).inspect => it writes ["a", "ab"] ; correct instead, if I execute: module ExtendedSlicer def slice(*args) arg0 = args[0] case arg0 when Regexp grep(arg0) else super end end end class Array include ExtendedSlicer end arr = Array.new %w{a b c ab} puts arr.slice(/a/).inspect # => can't convert Regexp into Integer (TypeError) Why? Maybe it is forbidden to include a Module in a built-in class, for security reasons, or... boh! :) Can you explain that? -- Posted via http://www.ruby-forum.com/.