What's the best way to create methods dealing with an object of acertain class?

Discussion in 'Ruby' started by Leif K-Brooks, Dec 3, 2003.

  1. I want to add a method to be run on Strings. Currently, I'm just adding
    it on to the String class. Should I be subclassing it instead? Creating
    a method which takes a String as an argument?
    Leif K-Brooks, Dec 3, 2003
    #1
    1. Advertising

  2. Leif K-Brooks

    Ben Giddings Guest

    Re: What's the best way to create methods dealing with an objectof a certain class?

    Lyle Johnson wrote:
    > Leif K-Brooks wrote:
    >> I want to add a method to be run on Strings. Currently, I'm just
    >> adding it on to the String class. Should I be subclassing it instead?
    >> Creating a method which takes a String as an argument?

    >
    > I have mixed feelings about re-opening built-in classes (like String) to
    > add new methods to them, even though the provision for this is one of
    > Ruby's attractions. My concern is that people get used to the built-ins
    > and expect certain standard behaviors from them; augmenting or otherwise
    > changing them could create confusion for other people looking at your code.


    I think one way this has been done very effectively is the "Time" class.
    The standard one contains a certain set of commands, but if you want more,
    you simply "require 'time'" and it now has a bunch more methods, like
    "iso8601".

    The other way this has been done very well is with 'yaml'. If you require
    this module, *everything* gains a "to_yaml" method. The name makes it
    clear that you shouldn't expect that method to appear without 'yaml'.

    As long as you're not changing the behaviour of any built-in methods, and
    you make it clear the methods aren't "native", you should be ok.

    Ben
    Ben Giddings, Dec 3, 2003
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Paul Miller

    best way of dealing with currency?

    Paul Miller, Oct 16, 2007, in forum: Python
    Replies:
    5
    Views:
    291
    Paddy
    Oct 17, 2007
  2. Oltmans
    Replies:
    6
    Views:
    340
    Terry Reedy
    Mar 11, 2009
  3. Voom
    Replies:
    3
    Views:
    578
    Ben Pfaff
    Oct 6, 2010
  4. Dan Tenenbaum
    Replies:
    1
    Views:
    93
    James Edward Gray II
    Dec 11, 2006
  5. Kenneth McDonald
    Replies:
    5
    Views:
    311
    Kenneth McDonald
    Sep 26, 2008
Loading...

Share This Page