![](/img/trans.png)
[英]Ruby - automatically initialize class instance variables of child classes without inheriting the value
[英]in Ruby can I automatically populate instance variables somehow in the initialize method?
在Ruby中我可以在initialize方法中以某種方式自動填充實例變量嗎?
例如,如果我有:
class Weekend
attr_accessor :start_date, :end_date, :title, :description, :location
def initialize(params)
# SOMETHING HERE TO AUTO POPULATE INSTANCE VARIABLES WITH APPROPRIATE PARAMS
end
end
您可以像這樣使用instance_variable_set
:
params.each do |key, value|
self.instance_variable_set("@#{key}".to_sym, value)
end
為了簡單起見:
class Weekend
attr_accessor :start_date, :end_date, :title, :description, :location
def initialize(params)
@start_date = params[:start_date] # I don't really know the structure of params but you have the idea
@end_date = params[:end_date]
end
end
你可以通過元編程的方式做一些更聰明的事情,但這真的有必要嗎?
Ruby有時可能很簡單。 看不到循環!
class Weekend < Struct.new(:start_date, :end_date, :title, :description, :location)
# params: Hash with symbols as keys
def initialize(params)
# arg splatting to the rescue
super( * params.values_at( * self.class.members ) )
end
end
請注意,您甚至不需要使用繼承 - 可以在創建期間自定義新的Struct
:
Weekend = Struct.new(:start_date, :end_date, :title, :description, :location) do
def initialize(params)
# same as above
end
end
測試:
weekend = Weekend.new(
:start_date => 'start_date value',
:end_date => 'end_date value',
:title => 'title value',
:description => 'description value',
:location => 'location value'
)
p [:start_date , weekend.start_date ]
p [:end_date , weekend.end_date ]
p [:title , weekend.title ]
p [:description, weekend.description ]
p [:location , weekend.location ]
請注意,這實際上並不設置實例變量。 你的課將有不透明的getter和setter。 如果您不想暴露它們,可以在它周圍包裝另一個類。 這是一個例子:
# this gives you more control over readers/writers
require 'forwardable'
class Weekend
MyStruct = ::Struct.new(:start_date, :end_date, :title, :description, :location)
extend Forwardable
# only set up readers
def_delegators :@struct, *MyStruct.members
# params: Hash with symbols as keys
def initialize(params)
# arg splatting to the rescue
@struct = MyStruct.new( * params.values_at( * MyStruct.members ) )
end
end
我想你可以簡單地說:
Weekend < Struct.new(:start_date, :end_date, :title, :description, :location)
然后在周末課程中添加其他內容:
class Weekend
#whatever you need to add here
end
我建議
class Weekend
@@available_attributes = [:start_date, :end_date, :title, :description, :location]
attr_accessor *@@available_attributes
def initialize(params)
params.each do |key,value|
self.send(:"#{key}=",value) if @@available_attributes.include?(key.to_sym)
end
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.