invoking class method within class definition

T

T.G.

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!
 
J

John Wilger

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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top