Joaquin Diaz
Joaquin Diaz

Reputation: 175

How do I get a fresh copy of an array in each iteration?

I cannot understand the following behavior

<% filter.each do |f| %>
   <% aux = @taxon_ids %>
   <%= check_box_tag "filter_taxon", aux << f[:id], @taxon_ids.include?(f[:id]) %>
   ...
<% end %>

for each loop of my function the aux var is not re-initializing. Indeed there is accumulating each id in him self.

Upvotes: 0

Views: 49

Answers (1)

smathy
smathy

Reputation: 27971

Unless you're assigning a new object (or one of the literal shorthands like []) then Ruby assignment is by reference, look:

[14] pry(main)> x = []          
=> []
[15] pry(main)> y = x           
=> []
[16] pry(main)> y << 1          
=> [1]
[17] pry(main)> x               
=> [1]

If you want your own copy of that array then use the .dup or .clone method:

aux = @taxon_ids.dup

Upvotes: 2

Related Questions