Weird understanding problem

Hello everyone,

I just went some steps back to some “basics” of Ruby.

When I read that everything is an object in Ruby, then i got confused by
one little example:

a = 3

=> a is referencing to “number object 3”

b = a

=> b is referencing to the same “number object 3” as a

a += 1

=> 4

b

=> 3

So i incremented the value of a by 1. When I take a look on b, then b is
still 3. That’s weird since b should refer to the same number object as
a does.

Quake L. wrote in post #1178805:

a += 1

Here you create a new int value, and ‘a’ refere to this new value.

That’s explain why a++ dosn’t exist.

see

ch. “Immutability and primitives”

As far as I understand it, “b” is an instance/object of a class, and
they are both object instances of Fixnum (b.class, a.class).

So when you create “b”, it creates a new Fixnum object with the value of
“a”, 3 in this instance, and that object is independent from “a”. You
are just using “a” to pass an argument to the new Fixnum object.

You can try the same with String, i.e. a=“a” and b=a, etc.

I guess what I’m driving at is that “a=b” doesn’t declare “relationship”
between the two objects, as algebra would, rather just a “shortcut” of
creating new Fixnum object “b” by using the current value of “a”.

Maybe your confusion comes from the fact that “a” and “b” are objects,
not variables? With variables, you can achieve what you are looking for:

@@a=3
@@b=@@a
@@a+=1

then both @@a and @@b will equal 4.

Or (maybe) even simpler explanation, by rewriting your post:

a = 3

=> a is creating new “number object 3”

b = a

=> b is creating new “number object 3”

Hey Andy,

sorry that I am answering that late. Thank your for the great
explanation.
Now things became clear to me. :slight_smile: