On Thursday, July 15, 2010 01:17:57 am Arun Kumar wrote:
> Hi All,
> 
> Could u please tell me what is the advantage is to use class methods
> over object method in ruby ?

Because the code "belongs" there, for whatever reason. For example, in 
ActiveRecord:

john = User.find_by_name('John Smith')
puts john.email

It really wouldn't make sense to make find_by_name an instance method, or to 
make email a class method.

> Which one is faster and what make it
> faster,

Neither. Both. The one that's doing what it's supposed to.

Let me see if I can make it clearer: There actually is no such thing as a 
class method in Ruby. Everything is an object, including classes -- class 
methods are just "object methods", or instance methods, on the class object.

Here, let me prove it to you:

File.read 'readme.txt'
f = File
f.read 'readme.txt'

See? The call to File.read was just another method call.

But, as an example, if the Rails core team had written ActiveRecord so it 
worked like this:

User.find_email_by_name('John Smith')
User.find_address_by_name('John Smith')

That's much harder to do efficiently than this:

john = User.find_by_name('John Smith')
john.email
john.address

I'm not saying instance methods are faster, they just make more sense in that 
specific case. It's like asking whether arrays or hashes are faster -- it 
depends entirely on what you're trying to do, and it's hardly even about speed 
-- if you know what they're meant for, you wouldn't really think to use an 
array instead of a hash, or vice versa.