我有一个类似的课程:
class Item
attr_accessor :item_id, :name, :address, :description, :facilities, :ratings, :directions, :geo, :images, :video, :availability
def self.create options={}
item = Item.new
item.item_id = options[:item_id]
item.name = options[:name]
item.description = options[:desc]
item.ratings = options[:rating]
return item
end
end
如何以这样的方式创建'create'方法,以便读取传递给定的选项并尝试创建它们而不必明确指定其名称?
即。没有item.name =选项[:item_id]等等....只是...计算机大脑认为“啊...我看到选项'选项[:name],让我尝试创建一个具有相同名称的属性这个值!......“
答案 0 :(得分:1)
class Item
attr_accessor :a, :b, :c
def initialize(options = {})
options.each {
|k,v|
self.send( "#{k.to_s}=".intern, v)
}
end
end
i = Item.new(:a => 1, :c => "dog" )
puts i.a
# outputs: 1
puts i.c
# outputs: "dog"
如果您感觉特别喜欢冒险:
class Object
def metaclass; class << self; self; end; end
end
class Item
def initialize(options = {})
options.each {
|k,v|
self.metaclass.send(:attr_accessor, k)
self.send( "#{k.to_s}=".intern, v)
}
end
end
i = Item.new(:a => 1, :c => "dog")
puts i.a
# 1
puts i.c
# dog
i2 = Item.new
puts i2.a
# ERROR