定义方法
define_method :hello |country,city|
puts "hello #{country}, I'm in #{city}"
end
hello('China' , 'XI\'AN') #=> hello China, I'm in XI'AN
简单模仿attr_accessor
class User
def self.setup_accessor var
define_method var do
instance_variable_get "@#{var}" #获取实例变量
end
define_method "#{var}=" do |value|
instance_variable_set "@#{var}", value
end
end
setup_accessor :name
setup_accessor :age
end
user = User.new
user.name = "kakarot"
puts user.name #=> kakarot
模仿attr_accessor 进阶
class User
def self.setup_accessor(*arg)
arg.each do |var|
define_method var do
instance_variable_get "@#{var}"
end
end
arg.each do |var|
define_method "#{var}=" do |value|
instance_variable_set "@#{var}" ,value
end
end
end
setup_accessor :name, :age
end
user = User.new
user.name = "kakarot"
p user.name #=> "kakarot"
遍历+define_method
class Myclass
attr_reader :name,:age
define_method :set_user do |name,age|
@name = name
@age = age
end
attributes = [:set_name, :set_age]
attributes.each do |method_name,attribute|
define_method method_name do |var|
@name = var if method_name == :set_name
@age = var if method_name == :set_age
end
end
end
obj = Myclass.new
obj.set_user("newton",43)
obj.send(:set_user,obj.name, 77)
puts "user name is #{obj.name}, user age is #{obj.age}"
user = Myclass.new
user.set_name('kakarot')
user.set_age(43)
puts "user name is #{user.name}, user age is #{user.age}"