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 silly, but I'm bored.
Anyway, I'm having trouble converting this kind of function to Ruby
void swap(int &a,int &b){
int c=b;
b=a;
a=c
}
What would be the equivalent ruby code inside a function ?
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).
In Ruby, arguments are passed by value. So the following method will never have any effect:
On the other hand, mosts objects are references, for examples strings, so you could write
This would swap the string values of the two arguments.
Integers are immediates, so there is no equivalent to
replace
; you can't writeswap_integers
.Anyways, in Ruby, you swap by writing
a, b = b, a