.
ruby extend() :
module SimpleModule
def self.class_hello_world
puts 'i am a simple module boss'
end
def self.class_hello_name
puts "hello from #{@@name}"
end
end
class SimpleClass
custom_extend SimpleModule
, :
module Dog
def self.greet
puts "hello"
end
end
class Cat
extend Dog
end
Cat.greet
--output:--
`<main>': undefined method `greet' for Cat:Class (NoMethodError)
extend() :
module Dog
def greet
puts "hello"
end
end
class Cat
extend Dog
end
Cat.greet
--output:--
hello
, extend() , (, , self)), Cattonton ( , Cat). ruby, include() extend() ( , self). :
- , .
def self.method_name - , .
def some_method
include() extend() # 2.
@@variables, , , @@variables , - . , .. @variables, def:
def my_extend(some_module)
singleton_class.include some_module
end
module Dog
def greet
puts @greeting
end
private
def sayhi
puts "hi"
end
end
class Cat
@greeting = "hello"
my_extend Dog
end
Cat.greet
Cat.class_eval {sayhi}
--output:--
hello
hi
my_include include.:)
my_include():
class Class
def my_include(module_)
module_.instance_methods(include_super=false).each do |meth_name|
meth = module_.instance_method(meth_name)
define_method(meth_name) do
meth.bind(self).call
end
end
module_.private_instance_methods(include_super=false).each do |meth_name|
meth = module_.instance_method(meth_name)
define_method(meth_name) do
meth.bind(self).call
end
private :"#{meth_name}"
end
end
end
module Dog
def greet
puts "hello"
end
def go
puts "run, run run"
end
private
def sayhi
puts "hi"
end
end
class Cat
my_include Dog
end
c = Cat.new
c.greet
c.go
c.sayhi
--output:--
hello
run, run run
my_extend():
class Class
def my_include(module_)
module_.instance_methods(include_super=false).each do |meth_name|
meth = module_.instance_method(meth_name)
define_method(meth_name) do
meth.bind(self).call
end
end
module_.private_instance_methods(include_super=false).each do |meth_name|
meth = module_.instance_method(meth_name)
define_method(meth_name) do
meth.bind(self).call
end
private :"#{meth_name}"
end
end
def my_extend(module_)
singleton_class.my_include module_
end
end
module Dog
def greet
puts @greeting
end
private
def sayhi
puts "hi"
end
end
class Cat
@greeting = "hello"
my_extend Dog
end
Cat.greet
Cat.class_eval {sayhi}
--output:--
hello
hi