Ruby: array is being passed by reference into function? -
this question has answer here:
- is ruby pass reference or value? 11 answers
i have simple code below
def testarray arr_tree = [1,2,3,4,5] (1..3).each |index| abcde(arr_tree) puts arr_tree[0] end end def abcde(node_tree) node_tree[0] += 100 end
so inside testarray function, have array arr_tree
being passed function abcde
. change value of array inside abcde
function , print array inside testarray
changed value here. output is
101 201 301
but expecting
1 1 1
please explain why results this? how can achieve expected result?
everything "passed object" in ruby.
and arrays objects.
if want avoid side-effects make copy of argument
def abcde(node_tree) copy = node_tree.dup copy[0] += 100 copy end
a note of caution though since named variable tree
, dup
method makes shallow copy only. shallow means array copied not elements.
why did not "pass reference" above?
"pass reference" concept language , not make sense in context of ruby. technically native implementation of ruby uses pass value, value pointer object structure. thinking of ruby using "pass value" misleading since not create copy of data structures before passed function. seems assumed happen…
Comments
Post a Comment