I'm new to Ruby and I'm having trouble understanding what's happening in this method.
I make this call in a Rails controller -
@arr = SomeClass.find_max_option(params[:x], @pos, params[:y], some_var)
I'm trying to return the value to @arr
, which happens successfully, but manipulations I make to @pos
within that method are being brought back as well; the value of @pos
changes when I'm only trying to get the value for @arr
.
Here's more details on the method
#before going into the method
@pos = [a,b]
def self.find_max_option(x, pos, y, some_var)
pos.collect! { |element|
(element == b) ? [c,d] : element
}
end
#new value of pos = [a, [c,d]] which is fine for inside in this method
... #some calculations not relevant to this question, but pos gets used to generate some_array
return some_array
But when the method is finished and gets back to the controller, the value of @pos
is now [a,[c,d]] as well.
What's going on here? I thought that pos
would be treated separately from @pos
and the value wouldn't carry back. As a workaround I just created a new local variable within that method, but I'd like to know what this is happening
#my workaround is to not modify the pos variable
pos_groomed = pos.collect { |element|
(element == b) ? [c,d] : element
}
end