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...

ac360
  • 7,735
  • 13
  • 52
  • 91
  • Where do you want to save the information? – lurker Sep 09 '13 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... – ac360 Sep 09 '13 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)? – HM1 Sep 09 '13 at 18:55
  • Only the length of the array will vary. – ac360 Sep 09 '13 at 18:55

2 Answers2

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
...
lurker
  • 56,987
  • 9
  • 69
  • 103
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

Community
  • 1
  • 1
Dmitry Matveev
  • 5,320
  • 1
  • 32
  • 43