0

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.

smathy
  • 26,283
  • 5
  • 48
  • 68
Joaquin Diaz
  • 184
  • 1
  • 5
  • 16

1 Answers1

2

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
smathy
  • 26,283
  • 5
  • 48
  • 68
  • For additional info on `#dup` vs `#clone` check out these links: https://ruby-doc.org/core-2.6.1/Object.html#method-i-dup-label-on+dup+vs+clone and https://stackoverflow.com/questions/10183370/whats-the-difference-between-rubys-dup-and-clone-methods – 3limin4t0r Mar 01 '19 at 20:25