Preferred way to call a class method?

C

Clint Pachl

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
 
R

Rick DeNatale

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
 

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

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,118
Latest member
LatishaWhy
Top