Question about defining class methods

R

Robo

When defining class methods, are these two ways the same? Is there a
preference on which one should be use?

class Monkey
def self.method1
puts "method1"
end

def Monkey.method2
puts "method2"
end
end

I would think self.method1 is more preferable 'cos it doesn't have to
get rename when the class name gets change.

Also, I see them get call in two different ways, Monkey.method1 and
Monkey::method1. Both seems to work, are they identical? Is there an
idiom on which way should be use?

Robo
 
T

T. Onoma

When defining class methods, are these two ways the same? Is there a
preference on which one should be use?

class Monkey
def self.method1
puts "method1"
end

def Monkey.method2
puts "method2"
end
end
Identical.

I would think self.method1 is more preferable 'cos it doesn't have to
get rename when the class name gets change.
True.

Also, I see them get call in two different ways, Monkey.method1 and
Monkey::method1. Both seems to work, are they identical? Is there an
idiom on which way should be use?

They are the same too. The only time they may differ is when a method begins
with a capital letter (which is very rare) then Monkey::Method1 would not
find it b/c it was looking for a constant called Method1 instead, to fix just
add (), i.e. Monkey::Method1().

T.
 
R

Robert Klemme

T. Onoma said:
They are the same too. The only time they may differ is when a method begins
with a capital letter (which is very rare) then Monkey::Method1 would not
find it b/c it was looking for a constant called Method1 instead, to fix just
add (), i.e. Monkey::Method1().

I think the general convention is to use "::" for constants and "." for
methods.

Kind regards

robert
 

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,764
Messages
2,569,564
Members
45,040
Latest member
papereejit

Latest Threads

Top