sscirrus
sscirrus

Reputation: 56719

Instance variable change affects Rails session

In the following code, the session variable array is being changed by an operation on an instance variable. How can I stop this from happening?

logger.debug session[:nav_ids].count # => 30
@ids = session[:nav_ids]
@ids.shift(10)
logger.debug session[:nav_ids].count # => 20

Upvotes: 1

Views: 93

Answers (2)

Jeremiah
Jeremiah

Reputation: 833

The way you are declaring the instance variable @ids, you are just pointing to session[:nav_ids].

You should be creating a new array:

@ids = Array.new(session[:nav_ids])

...or cloning like @zwippie suggests.

Upvotes: 0

zwippie
zwippie

Reputation: 15515

You could clone or dup the ids:

@ids = session[:nav_ids].clone

Now you can alter @ids without affecting session[:nav_ids].

Upvotes: 1

Related Questions