Class Methods and Instance Methods

A

arose

I'm reading Why's (Poingnant) Guid to Ruby chapter 3.

Class methods vs. Instance methods is mentioned.

This is what he says:

class methods are usually attached after variables and constants.
Rather than a dot, a double colon is used.
Door::new( :eek:ak )

I talked some in this group about a little program I wrote.
g=File.open(readfile,"r")
g.each_line {|readline| File.new((readline).chomp, "w")}

Now File is a class correct?

Why not File::new in the second line of code above?
 
D

Dave Burt

arose said:
I'm reading Why's (Poingnant) Guid to Ruby chapter 3.

Class methods vs. Instance methods is mentioned.

This is what he says:

class methods are usually attached after variables and constants.
Rather than a dot, a double colon is used.
Door::new( :eek:ak )

I talked some in this group about a little program I wrote.
g=File.open(readfile,"r")
g.each_line {|readline| File.new((readline).chomp, "w")}

Now File is a class correct?

Why not File::new in the second line of code above?

Both are allowed. They're two ways of saying the same thing. You can
also use the double-colon to call instance methods:

"foo"::length

Now, the reason for this is simple. Class methods ARE instance methods,
because classes themselves are objects.

By convention, the double-colon seems generally reserved for class
methods. I've never seen it used other than after a capitalised class
constant: Foo::bar.

A lot of people use the dot always, though. I think that keeps things
clearer; I see no reason to use a second operator when the first does
the job.

Cheers,
Dave
 
A

arose

Exactly what I was looking for, thanks.



Dave said:
Both are allowed. They're two ways of saying the same thing. You can
also use the double-colon to call instance methods:

"foo"::length

Now, the reason for this is simple. Class methods ARE instance methods,
because classes themselves are objects.

By convention, the double-colon seems generally reserved for class
methods. I've never seen it used other than after a capitalised class
constant: Foo::bar.

A lot of people use the dot always, though. I think that keeps things
clearer; I see no reason to use a second operator when the first does
the job.

Cheers,
Dave
 

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,997
Messages
2,570,239
Members
46,827
Latest member
DMUK_Beginner

Latest Threads

Top