Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > invoking class method within class definition

Reply
Thread Tools

invoking class method within class definition

 
 
T.G.
Guest
Posts: n/a
 
      11-04-2005
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!

 
Reply With Quote
 
 
 
 
John Wilger
Guest
Posts: n/a
 
      11-04-2005
On 11/3/05, T.G. <(E-Mail Removed)> 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


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Jar Class Loader (JCL) and invoking method with my class from jarfile gorudonu Java 0 08-05-2010 05:56 PM
invoking destructor from within instance method Fred C++ 4 06-04-2008 08:41 AM
Help - Invoking my servlets without specifying a definition in the web.xml file stevenmac2 Java 1 08-23-2007 03:53 AM
can a class definition inside another class's definition Jianli Shen C++ 1 03-13-2005 06:02 PM
aliasing an external method from within a method definition? Francis Hwang Ruby 4 03-08-2005 08:45 AM



Advertisments