Ruby array into an object instance -
i've made array generator fake individuals populate apartments:
["53 york street", 7995, true, 123, 2, 1, "tommy gough"] ["53 york street", 18070, true, 278, 2, 1, "sarah stewart"]
but want turn each instance object instance , i'm trying figure out .each loop (or other) method so. haven't found way write method doesn't use string output... i'm going wrong.
say class want instances of looks this:
apartment = struct.new(:street, :code, :field3, :field4, :field5, :field6, :name)
(i don't know other fields stand for.)
and input looks this:
input = [ ["53 york street", 7995, true, 123, 2, 1, "tommy gough"], ["53 york street", 18070, true, 278, 2, 1, "sarah stewart"] ]
then can create array of instances this:
output = input.map { |entry| apartment.new(*entry) }
note splat (*
) expands (inner) array list of method arguments can pass constructor. more verbose way write be:
output = [] input.each |entry| output << apartment.new(*entry) end
Comments
Post a Comment