[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Preferred way to call a class method?

Clint Pachl

10/15/2006 12:27:00 AM

class Test
def self.class_meth
'inside class method'
end

def inst_meth1
self.class.class_meth
end

def inst_meth2
Test.class_meth
end
end

What is the preferred way of calling a class method from within an
instance method, <Class Object>.<class method> or self.class.<class method>?

What are the side effects to either method?

-pachl
1 Answer

Rick DeNatale

10/15/2006 1:05:00 AM

0

On 10/14/06, Clint Pachl <pachl@ecentryx.com> wrote:
> class Test
> def self.class_meth
> 'inside class method'
> end
>
> def inst_meth1
> self.class.class_meth
> end
>
> def inst_meth2
> Test.class_meth
> end
> end
>
> What is the preferred way of calling a class method from within an
> instance method, <Class Object>.<class method> or self.class.<class method>?
>

In the first case the class_meth will be sent to the receivers class,
while in the second it will always be sent to Test.

If there are subclasses of Test there can be a difference

class Test

def self.class_meth
puts "Test's class method called"
end

def inst_meth1
self.class.class_meth
end

def inst_meth2
Test.class_meth
end

end

class Test1 < Test
def self.class_meth
puts "Test1's class method called"
end

end

irb(main):023:0> Test1.new.inst_meth1
Test1's class method called
=> nil
irb(main):024:0> Test1.new.inst_meth2
Test's class method called



--
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denh...