【发布时间】:2020-01-22 13:15:22
【问题描述】:
我有一个名为 Person 的类,方法正在添加到名称、描述、昵称中
但是这些实例方法确实有相同的代码集
class Product
def name
p "this is the name of the product"
end
def description
p "this is the descriptions of the product"
end
def nick_name
p "this si the description of the nick name"
end
end
class Person < Product
%w(name description nick_name).map{|attr| attr.to_sym}.each do |definable_method|
define_method definable_method do
print "this is the #{definable_method} in the person"
super
end
end
end
p1 = Person.new
p1.name
预期结果
this is the name in the person
this is the name of product
p1.description
预期结果
this is description in the person
this is the descriptions of product
【问题讨论】:
标签: ruby-2.0