Preferred way to call a class method?

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, . or self.class.?

What are the side effects to either method?

-pachl

On 10/14/06, Clint P. [email protected] wrote:

 Test.class_meth

end
end

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

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.denhaven2.com/

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs