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. 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. Eric Lilja
    Replies:
    2
    Views:
    342
    Eric Lilja
    Aug 14, 2007
  2. Michael Perle
    Replies:
    4
    Views:
    133
    Michael Perle
    May 23, 2006
  3. Raj Singh
    Replies:
    2
    Views:
    213
    Rick DeNatale
    May 29, 2008
  4. Greg Hauptmann
    Replies:
    9
    Views:
    263
    Loren Segal
    Jun 16, 2008
  5. Matthew Pounsett

    Getting a usable reference to an OO method

    Matthew Pounsett, Jul 27, 2011, in forum: Perl Misc
    Replies:
    0
    Views:
    118
    Matthew Pounsett
    Jul 27, 2011
Loading...

Share This Page