From: Chris Carter Date: 2007-02-26T04:08:36+09:00 Subject: Re: Class method declarations help On 2/25/07, Eckie Silapaswang wrote: > Hope everyone is having a great weekend! I was looking over some code > concerning class method declarations as shown below: > > #2 > class Animal > attr_accessor :species, :form > > def self.create_from_hash(hash) > a = new > a.species = hash[:species] > a.form = hash[:form] > a > end > end > Animal::create_from_hash(:species => :fox, :form => :cartoon) # => > > #3 > class Animal > attr_accessor :species, :form > > class < def create_from_hash(hash) > a = Animal.new > a.species = hash[:species] > a.form = hash[:form] > a > end > end > end > Animal::create_from_hash(:species => :fox, :form => :cartoon) # => > > The lines of particular interest to me are the > > def self.create_from_hash(hash) > > and the > > class << self > def create_from_hash(hash) > > I remember reading from the "Ruby for Rails" book that there's a "subtle > difference between these two approaches to defining a singleton method, > involving the scope of constants, but that's an arcane point. For the > most part, you can treat them as equivalent". > > My questions to all the Rubyists out there is, do you have a particular > preference between the two choices? Is this a style issue? Or is there > really a concrete "it depends on this" factor? > > Best regards, > > Eckie > > -- > Posted via http://www.ruby-forum.com/. > > Hi Eckie, Generally speaking, if you only have 1 or 2 class methods you use the self.method syntax, and if you have a lot of class methods you use the class<