Method usable as instance and as class method

Discussion in 'Ruby' started by Michael Perle, May 19, 2006.

  1. Hi Ruby Folks,

    What do you think would be the best way
    to provide one and the same method as a
    class method and as an instance method.

    I did not find any examples, and am asking myself
    if the call of the class method from the instance
    method is the real thing.

    1. Is there a better way?
    2. Does it make any difference if I use
    'def self.method' or 'def ClassName.method'
    3. Why does self.method not work in the def of
    an instance method? (See 2nd comment below.)

    --- Start of sample code ---

    class TextCase

    def self.up(txt)
    # Would TextCase.up(txt) be any different?
    txt.upcase
    end

    def up(txt)
    TextCase.up(txt)
    # Why not self.up(txt)?
    # Tried it and got a 'stack level too deep ...' error
    end

    end

    tc = TextCase.new
    puts tc.up('abc')
    puts TextCase.up('def')

    --- End of sample code ---

    Thank you very much for your ideas.
    MP
     
    Michael Perle, May 19, 2006
    #1
    1. Advertisements

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. Sridhar R
    Replies:
    14
    Views:
    1,771
    =?iso-8859-1?Q?Fran=E7ois?= Pinard
    Feb 10, 2004
  2. marekw2143
    Replies:
    3
    Views:
    1,597
    marekw2143
    Jul 25, 2009
  3. Martin P. Hellwig
    Replies:
    1
    Views:
    507
    Martin P. Hellwig
    Mar 26, 2010
  4. David Garamond
    Replies:
    5
    Views:
    451
    Ara.T.Howard
    Jun 8, 2004
  5. Michael Perle
    Replies:
    4
    Views:
    258
    Michael Perle
    May 23, 2006
  6. Raj Singh
    Replies:
    2
    Views:
    345
    Rick DeNatale
    May 29, 2008
  7. Greg Hauptmann
    Replies:
    9
    Views:
    495
    Loren Segal
    Jun 16, 2008
  8. Chuck Remes
    Replies:
    3
    Views:
    394
    hemant
    Aug 12, 2010
Loading...