Ruby – Variables

Variables are used to keep track of objects. Each variable holds a reference to an object.

person1 = "Tim"

person2=person1

person1[0] = 'J'

#{person1} produces Jim

#{person2} produces Jim

In Ruby, strings are mutable, unlike Java. Assigning person1 to person2 doesn’t create any new objects. It simply copies person1’s object reference to person2, so that both variables refer to the same object.

Duplicating String Objects

You can use the dup method to create a string object with identical contents.

person2 = person1.dup

Freezing String Objects

To prevent anyone from changing a particular object, freeze it. You will raise a RunTimeError when attempting a frozen object.

person1.freeze