1

My array contains a varying amount of objects. I need to iterate through the array and save each object id as a unique variable. Given the amount of objects within the array will vary, how should I do this?

"items"=>[{"id"=>"B00668BTCI"}, {"id"=>"B0041KJSL2"}]

I need to save the information to a new object that can support up to 16 IDs. @object.id_one, @object.id_two, etc...

4
  • Where do you want to save the information? Commented Sep 9, 2013 at 18:51
  • I need to save the information to a new object that can support up to 16 IDs. object.id_one, object.id_two, etc... Commented Sep 9, 2013 at 18:53
  • Will the array contain entirely different objects (i.e. a mixture of strings, hashes, arrays, numbers) or only the length of the array will vary (i.e. 2 or 10 or 200 hash elements as shown above)? Commented Sep 9, 2013 at 18:55
  • Only the length of the array will vary. Commented Sep 9, 2013 at 18:55

2 Answers 2

3

The suitable way to save your data all depends upon how you want to reference it or access it later. Meta-programming is interesting and fun, but may be overkill depending upon your needs. You will need to determine that after looking at the choices. An alternative way is in an array:

array_of_ids = items.map(&:values).flatten

Or

array_of_ids = items.map { |item| item["id"] }

Then all of the IDs are in the array array_of_ids and becomes, in your example:

["B00668BTCI", "B0041KJSL2"]

Accessible by:

array_of_ids[0]  # first id
array_of_ids[1]  # second array
...
Sign up to request clarification or add additional context in comments.

Comments

1

You need to do some meta-programming here...
Here is a post for you, it has an answer (by Chirantan) that shows how to create instance variables dynamically.

Hope this helps.

EDIT
Just in case you get interested to learn more, I have also found a good article about creating methods dynamically, check it out.

Dynamically adding class methods in Ruby by Ryan Angilly

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.