I have this simple test:
def swap(a, b)
c = a
a = b
b = c
end
a = 3
b = 4
swap(a, b)
print a # 3. not change value
I know this example will not work on some languages such as Java or C# because those variables are primitives. But in Ruby, if everything is an object, I think the above example should work. Please explain this to me.
I think the problem is because FixNum is immutable. I have proof-of-concept code using Java to make an integer class that is not immutable:
static class CustomInteger {
Integer value;
public CustomInteger(int i) {
this.value = i;
}
public void changeValue(int i) {
this.value = i;
}
public int getValue() {
return value;
}
public CustomInteger setValueImmutable(int i) {
return new CustomInteger(i);
}
}
public static void swap(CustomInteger a, CustomInteger b) {
int c = a.getValue();
a.changeValue(b.getValue());
b.changeValue(c);
}
public static void main(String[] args) {
CustomInteger i1 = new CustomInteger(3);
CustomInteger i2 = new CustomInteger(4);
swap(i1, i2);
System.out.println(i1.getValue());
}
public static void notWorkSwap(Integer a, Integer b) {
int temp_a = a;
int temp_b = b;
a = temp_b;
b = temp_a;
}