düşündürmektedir. Görünürde döngü yok!
Weekend = Struct.new(:start_date, :end_date, :title, :description, :location) do
def initialize(params)
# same as above
end
end
Testi:
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 ]
Not yapar değil - hatta miras kullanmayı gerekmez
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
Not yeni Struct
oluşturulması sırasında özelleştirilebilir aslında örnek değişkenleri ayarlayın. Sınıfınız opak alıcılara ve ayarlayıcılara sahip olacak. Bunları ifşa etmeyi tercih ederseniz, etrafınızdaki başka bir sınıfa sarılabilirsin.
# 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
ve işaretlemeyi bkz İşte bir örnek şımarık ... – apneadiving
Gereksiz metaproglardan sakınma arzusunu anlıyorum, fakat bu OP'nin sorduğu özlü kod değil. Her alan adını manuel olarak belirtmeniz gerekir. – Kelvin