module Homable
def has_home?
true
end
end
class Cat
include Homable
def has_home?
false
end
end
Cat.new.has_home?
Cat.ancestors
Prepend
module Homable
def has_home?
true
end
end
class Cat
prepend Homable
def has_home?
false
end
end
Cat.new.has_home?
Cat.ancestors
Extend
module Homable
def has_home?
true
end
end
class Cat
extend Homable
end
Cat.has_home?
### define_method, instance_variable_get, instance_variable_set
Добавление метода экземпляру
class Cat
define_method 'eat' do |food|
"#{food}'s yammy!"
end
end
cat = Cat.new
cat.eat 'whiskas'
Чтение переменной экземпляра
class Cat
def initialize string
@color = string
end
end
cat = Cat.new("black")
cat.instance_variable_get "@color"
Запись переменной экземпляра
class Cat
end
cat = Cat.new()
cat.instance_variable_set "@color", "black"
Добавление методов классу
class Cat
def self.my_attr_accessor *attributes
attributes.each do |attribute|
# Getter
define_method attribute do
self.instance_variable_get "@#{attribute}"
end
########
# Setter
define_method "#{attribute}=" do |value|
self.instance_variable_set "@#{attribute}", value
end
########
end
end
my_attr_accessor :name, :age, :weight
def initialize name, age, weight
@name, @age, @weight = name, age, weight
end
end