invoking class method within class definition

Discussion in 'Ruby' started by T.G., Nov 4, 2005.

  1. T.G.

    T.G. Guest

    Hi,
    consider following code:

    #!/usr/bin/env ruby
    class Foo
    def self.bar
    puts "class method called"
    end

    def some_method
    Foo.bar # -----> self.bar will not work here
    end
    end

    foo = Foo.new
    foo.some_method

    although I can define the class method using "self", I have to use
    class name to invoke the class method within the class. it would be
    nice if I can invoke class method without explicitly using it's name,
    so when I change my class name, I only need to change it in one place.
    any way to do this?

    Thanks!
     
    T.G., Nov 4, 2005
    #1
    1. Advertising

  2. T.G.

    John Wilger Guest

    On 11/3/05, T.G. <> wrote:
    > class Foo
    > def self.bar
    > puts "class method called"
    > end
    >
    > def some_method
    > Foo.bar # -----> self.bar will not work here
    > end
    > end


    def some_method
    self.class.bar
    end

    will do what you want. Remember that inside #some_method, "self"
    refers to the instantiated object, not the class itself.

    --
    Regards,
    John Wilger

    -----------
    Alice came to a fork in the road. "Which road do I take?" she asked.
    "Where do you want to go?" responded the Cheshire cat.
    "I don't know," Alice answered.
    "Then," said the cat, "it doesn't matter."
    - Lewis Carrol, Alice in Wonderland
     
    John Wilger, Nov 4, 2005
    #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. Jianli Shen
    Replies:
    1
    Views:
    642
    Victor Bazarov
    Mar 13, 2005
  2. stevenmac2
    Replies:
    1
    Views:
    624
    stevenmac2
    Aug 23, 2007
  3. Fred
    Replies:
    4
    Views:
    302
    sumsin
    Jun 4, 2008
  4. gorudonu
    Replies:
    0
    Views:
    1,067
    gorudonu
    Aug 5, 2010
  5. Francis Hwang
    Replies:
    4
    Views:
    137
    Pit Capitain
    Mar 8, 2005
Loading...

Share This Page