6

So in Ruby, everything is passed to functions by value. However, when you manipulate objects, you're actually manipulating references. A simple example:

```
a = [3]
b = a
c = a
b.push(2)
print a
print b
print c

# => [3, 2][3, 2][3, 2]
```

Here's a more complicated example from the problem I was solving:

```
table = Array.new(5) { Array.new() }
1.upto(5 - 1) do |i|
1.upto(5 - 1) do |j|
table[i] = table[j]
end

table[i] << rand(1..6)
end
```

I have been running around in circles this morning because I forgot that. This makes C++ for example, more clear than Ruby since C++ explicitly shows the intent to the programmer.

Comments
  • 4
    Well I‘m not familiar with ruby but this looks like it handles it like most high level languages do.
    The kind of type determines if its instance is passed by value or by reference.
    For example, structs are used as value types and classes are used as reference types. But instances of both are referred to as objects.
    So it is clear what is happening. C++ is just different in that it doesn’t handle value/reference semantics at the type declaration but at the usage of the instances and declaration of the variables.
  • 1
    This makes C++ slightly less convenient but more flexible, imho.
  • 0
    Sounds like JS
  • 2
    I may have mixed passing primitives and passing objects (which happens by reference) but my point was that in language like C or C++ it is clear whether or not the current declared variable is of a concrete value or a reference to some value/memory. That's what I meant by explicit intent in that regard.
  • 1
    That is why you .copy objects :D
Add Comment