I have a multi-dimensional array called my_ids_and_names
It should probably be a hash but lets leave it as an array for now 🙂
I create it with: my_own_array = Array.new[10],[2]
I have a variable @my_ids which has the id’s that I want.
I populate it within a method like this:
# Setup
@my_ids_and_names = Array.new[10],[2]
@my_ids.each do |cid|
@my_ids_and_names[cid][1] = my_id
@my_ids_and_names[cid][2] = MyModel.find(my_id).internal_name
end
@my_ids_and_names
Now I want to retrieve information in views.
I am trying:
<% @campaign_ids_and_names.each do |cid, nm| %>
"various bits of code..."
var_for_id = cid
var_for_nm = nm
<% end %>
Will the cid and nm be set correctly?
I want the loop to be able to spit out the cid/names as in
id name
4 brick
9 tile
45 grout
Right now I am getting The error occurred while evaluating nil.[]= in the setup
If you fire up
irbconsole, you’ll see thatArray.new[10],[2]is not creating an array you wanted, instead it creates the following array:If you want to create a new array with 10 array elements, use the following constructor:
Update 1
But as reading your question further I can see that you need a
Hashinstead of anArray, and you should keep in mind that ruby starts to index from0instead of1.So:
Which can be further simplified to:
Update 2
But that won’t work with your
eachloop what you’ve provided, so I would use the following code instead:This will create a
Hashwithcidkeys and theinternal_nameofMyModelsas values.