Stefano Crocco
4/7/2008 9:12:00 AM
On Monday 07 April 2008, Yu-shan Fung wrote:
> Pretty dumb question -- how do I call a class method from inside an
> instance method (of the same class)?
>
> The use case I have is that in an activerecord model class, I would like
> to define an instance method which calls find_by_sql.
>
> I have tried and found that this works:
> self.class.find_by_sql
>
>
> But this seems pretty verbose for something so obvious.
>
> Thanks!
You can replace self.class with the name of the class. For example:
class C
def C.x
end
def y
self.class.x
C.x
end
end
There's a difference, however. If you derive a class from C and override C.x
from D:
class D < C
def self.x
end
end
using self.class.x from C#y will use the version of x defined in the
instance's class (that is, C.x if called by an instance of C and D.x if called
by an instance of D). Using C.x will, obviously, always call C.x. Here's some
code which demonstrates this:
class C
def self.x
puts "x of C"
end
def y
self.class.x
end
def z
C.x
end
end
class D < C
def self.x
puts "x of D"
end
end
puts "Calling y on an instance of C"
C.new.y
puts "Calling y on an instance of D"
D.new.y
puts "Calling z on an instance of D"
D.new.z
I hope this helps
Stefano