ruby - How do I stop a defined method from mutating the argument passed to it? -


i'm picking fundamentals of ruby, , stumbled upon can't figure out. here's simple version of it, figure out concepts involved.

suppose define method this:

def no_mutate(array)   new_array = array   new_array.pop end 

now call method:

a = [1, 2, 3] no_mutate(a) 

i expect printing give: [1, 2, 3] instead, gives: [1, 2]

since i've defined new variable , pointed whatever array i'm passing in, , modifying new variable, why array i'm passing in being mutated? in example, why no_mutate mutate 'a'? how avoid mutating 'a'?

as others have said have create copy, either using array.clone or array.dup. reason happens becuase ruby both pass value , pass reference.

for example:

a = 'hello' b =  b << ' world'  puts #=> "hello word" 

this happens because b new variable it's points same memory location a, when b changes in way doesn't create new object in way (such using << operator) a change well.

that why have duplicate or clone create variable has it's own copy of data rather variable points same copy original.


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - Bypass Geo Redirect for specific directories -

php - .htaccess mod_rewrite for dynamic url which has domain names -