as a way to spice up my C++ programming homework, I\'ve decided to instead of typing the C++ from the book onto my computer, instead reforming it in Ruby. Yes it\'s a bit si
In Ruby, arguments are passed by value. So the following method will never have any effect:
def doesnt_swap(a, b)
c = a
a = b
b = c
end
On the other hand, mosts objects are references, for examples strings, so you could write
def swap_strings(a, b)
c = a.dup
a.replace(b)
b.replace(c)
end
This would swap the string values of the two arguments.
Integers are immediates, so there is no equivalent to replace
; you can't write swap_integers
.
Anyways, in Ruby, you swap by writing a, b = b, a
Ruby is strictly pass-by-value. Always. But sometimes those values are poointers.
Here's a couple of links:
Note that while all of these say "Java", they should really say "Smalltalk and its descendants", which includes Java, Ruby and a ton of other languages.
I think most of the confusion stems from two problems:
BTW: I deliberately misspelt "poointers" with an OO for object-orientation to make it clear that I am not talking about raw memory addresses, I am talking about opaque references to objects (and for obvious reasons I do not want to use the word "reference"; if you know a better word that is neither "pointer" nor "reference", I'd love to hear it).