E
Eckie Silapaswang
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_hashspecies => :fox, :form => :cartoon) # =>
#3
class Animal
attr_accessor :species, :form
class <<self
def create_from_hash(hash)
a = Animal.new
a.species = hash[:species]
a.form = hash[:form]
a
end
end
end
Animal::create_from_hashspecies => :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
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_hashspecies => :fox, :form => :cartoon) # =>
#3
class Animal
attr_accessor :species, :form
class <<self
def create_from_hash(hash)
a = Animal.new
a.species = hash[:species]
a.form = hash[:form]
a
end
end
end
Animal::create_from_hashspecies => :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