0

I've made an array generator for fake individuals to populate apartments:

["53 York Street", 7995, true, 123, 2, 1, "Tommy Gough"]
["53 York Street", 18070, true, 278, 2, 1, "Sarah Stewart"]

but I want to turn each instance into an Object Instance and I'm trying to figure out an .each loop (or other) method to do so. I haven't found a way to write a method that doesn't use a string for output... but I'm probably going about it wrong.

1
  • 2
    Do you have a class that has these fields? Commented Nov 13, 2014 at 13:47

1 Answer 1

1

Say the class that you want instances of looks something like this:

Apartment = Struct.new(:street, :code, :field3, :field4, :field5, :field6, :name)

(I don't know what the other fields stand for.)

And say your input looks like this:

input = [
  ["53 York Street", 7995, true, 123, 2, 1, "Tommy Gough"],
  ["53 York Street", 18070, true, 278, 2, 1, "Sarah Stewart"]
]

Then you can create an array of instances like this:

output = input.map { |entry| Apartment.new(*entry) }

Note the splat (*) that expands the (inner) array to a list of method arguments that you can pass to your constructor. A more verbose way to write this would be:

output = []
input.each do |entry|
  output << Apartment.new(*entry)
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.