[prev in list] [next in list] [prev in thread] [next in thread] 

List:       ruby-talk
Subject:    Re: Is better to subclass or to add methods to an existing class?
From:       Dan Debertin <airboss () nodewarrior ! org>
Date:       2002-09-19 13:46:26
[Download RAW message or body]

Subclassing is, I think, the thing to do if you need to extend the
behavior of a class. The case where method-adding becomes useful is
when you need to extend Ruby itself, because subclassing doesn't alter
the anonymous operators or the classes of object returned by Ruby's
builtin methods.

For example, if you add a specialized sort function to Hash:

class MyHash < Hash
  def sortedkeys
    keys.sort
  end
end

a = { "foo" => "bar" }

'a' will still be a Hash, not a MyHash. There's no way to tell the {}
constructor to return a MyHash.

And builtins will still return builtin classes:

class MyString < String
  def rot13
    tr("A-Za-z", "N-ZA-Mn-za-m")
  end
end

hex = sprintf("0x%x", 12345)

'hex' will be an ordinary String, not a MyString. If you tried to do
this with subclassing, you'd have to convert everything that came out
of an anonymous constructor or builtin method into the subclassed
object, which would be tedious.

Dan
--
/^Dan Debertin$/         
airboss@nodewarrior.org  | Did I sleep a little too late,
www.nodewarrior.org      | or am I awake?        --Byrne



[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic