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.

Kind regards

robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

-- 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

Reply via email to