0

When running this code:

def someFunction(someArray)
  (0...(someArray.size)).each do |i| someArray[i] += 1 end
  return someArray
end

array = [0, 1, 2]
someFunction(array) # => [1, 2, 3]
array # => [1, 2, 3]

array is changed. In C, arrays are passed as pointers but I thought Ruby does't do 'pass by reference'. What is happening here and how can I make sure a method is not changing something outside it's scope?

sawa
  • 165,429
  • 45
  • 277
  • 381
cvb0rg
  • 73
  • 6
  • 3
    You're mistaken. Ruby objects (excepting primitives like Fixnums) are passed by reference. If you don't want a method to be able to modify an object, pass it a copy instead with `obj.dup`. – Jordan Running Feb 03 '16 at 02:13
  • 2
    "In C, arrays are passed as pointers but I thought Ruby does't do 'pass by reference'" – Ruby is *exactly* like C. Ruby is *always* pass-by-value, just like C. And, similar to C, the value being passed is *always* a pointer. (In C, you can choose to either pass the value or a pointer to the value. In Ruby, you don't have that choice. You always pass a pointer.) – Jörg W Mittag Feb 03 '16 at 02:43
  • And Ruby behaves exactly like C: you cannot mutate the variable binding (because Ruby uses pass-by-value), but you *can* follow the pointer and mutate the value which is at the other end of the pointer (because Ruby is not a purely functional language, mutating state is possible). It behaves *exactly* like C does: if I follow the pointer to an array, and mutate the memory location, then other methods who also have their own pointer to that memory location, will see that modification. – Jörg W Mittag Feb 03 '16 at 02:43
  • Ruby is pass-by-value but the values are references so your methods should duplicate/copy their arguments unless they explicitly want to (and are documented to) alter their arguments. – mu is too short Feb 03 '16 at 02:44
  • "What is happening here" – It's called *mutable state*. Some languages don't have it (e.g. Haskell, Clean), but most do. – Jörg W Mittag Feb 03 '16 at 02:46

0 Answers0