Ruby - method changes input variable value -
Ruby - method changes input variable value -
i'm new ruby , i'm having problem understanding what's happening in method.
i create phone call in rails controller -
@arr = someclass.find_max_option(params[:x], @pos, params[:y], some_var) i'm trying homecoming value @arr, happens successfully, manipulations create @pos within method beingness brought well; value of @pos changes when i'm trying value @arr.
here's more details on method
#before going 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]] fine within in method ... #some calculations not relevant question, pos gets used generate some_array homecoming some_array but when method finished , gets controller, value of @pos [a,[c,d]] well.
what's going on here? thought pos treated separately @pos , value wouldn't carry back. workaround created new local variable within method, i'd know happening
#my workaround not modify pos variable pos_groomed = pos.collect { |element| (element == b) ? [c,d] : element } end
instead of using collect!, utilize collect (without !). so, rewrite method as:
def self.find_max_option(x, pos, y, some_var) pos.collect { |element| (element == b) ? [c,d] : element } end when using ! version of collect, replacing each element value returned block. however, when using collect without !, new array created, , object collect beingness called doesn't changed. see docs:
collect! vs collect
using ! @ end of method name mutual practice in ruby. this question related , worth taking look.
ruby-on-rails ruby
Comments
Post a Comment