The Ruby concept of methods and classes just for a particular object.
--The singular method build_greeting
belongs only to the string object referenced by the variable message
at the time of definition.
message = "Hello" #String object
def message.build_greeting(target)
"#{self}, #{target}."
end
message.build_greeting("world") # => Hello, world.
message2 = "Hello" #Objects with the same value but different values
message2.build_greeting("world") # => NoMethodError
--A GoF design pattern that guarantees that only one instance of that class will be created.
CENTRAL_REPOSITORY = Object.new
def CENTRAL_REPOSITORY.register(target)
@registered_objects ||= []
unless @resgistered_objects.include? target
@registered_objects << target
end
end
def CENTRAL_REPOSITORY.unregister(target)
@registered_objects = []
@registered_objects.delete(target)
end
--The definition expression of the singular class is described as "<< (object)
" in the class
expression.
--The object CENTRAL_REPOSITORY
now belongs to the singular class(CENTRAL_REPOSITORY)
.
--Instance methods added to the singular class (CENTRAL_REPOSITORY)
can be called on the object CENTRAL_REPOSITORY
.
CENTRAL_REPOSITORY = Object.new
class << CENTRAL_REPOSITORY
def register(target)
@registered_objects ||= []
unless @registered_objects.include? target
@registered_objects << target
end
end
def unregister(target)
@registered_objects ||= []
@registered_objects.delete(target)
end
end
-** A singular method is an instance method of a singular class **. ――In other words, what is happening in the above two examples is the same.
-** A class method is a singular method ** of a Class
object.
--The pseudovariable self
refers to Duration
itself, so a_week_from
is a peculiar method of Duration
.
class Duration
def self.a_week_from(from)
return self.new(from, from+7*24&60*60)
end
end
p Duration.a_week_from(Time.now)
-** A metaclass is a singular class ** of a Class
object.
--The singular class (Duration)
is also called the metaclass of Duration
.
class Duration
class << self # self(=Duration)Define a singular class for
def a_week_from(from)
return self.new(from, from+7*24*60*60)
end
end
end
p Duration.a_week_from(Time.now)
I was impressed by understanding that "the class of the A
class is the Class
class (= the A
class is the Class
object)".
-First Ruby -Ruby Metaclass Hierarchy -Ruby beginner's class << self story (or singular and metaclass) -After all, what is a Ruby peculiar method? -[Ruby] About singular methods
Recommended Posts