Mikk Poles Mikk Poles - 4 months ago 10
Ruby Question

String Replace Ruby

I am trying to play around my codes in ruby.

Here's what I got:

name = "Rol"
title = name
name = "Sam"
puts name
puts title

OUTPUT:
Sam
Rol

name = "Rol"
title = name
name.replace("Sam")
puts name
puts title

OUTPUT:
Sam
Sam


Basically I wondering why when I use reassignment equal sign it changes just the variable name and left the title with the old value. However upon using the replace method, it changes the value of both?

Any explanation in layman's term on this? Newbie in ruby here.

Answer

The simple layman terms are:

  • Assignments change variables.

  • Mutation methods change objects.

Variables and objects are different things in Ruby. Each variable is a label that points to an object. Each method call is sent to an object. For convenience we often simplify discussion, because it is easy to say "The name is 'Sam'" when in detail we mean "The value stored in the String object pointed to by the name variable is 'Sam'"

In your first example:

The line name = "Rol" creates a new String object from the literal "Rol" and points the local variable name at it.

The line title = name points the local variable title to the same String object.

The line name = "Sam" creates a new String object from the literal "Sam" and points the local variable name at it. Now name and title point to different String objects.

At this point there are two independent String variables, with two different variables pointing at them, so any uses of them remain separate.

In your second example:

The line name = "Rol" creates a new String object from the literal "Rol" and points the local variable name at it.

The line title = name points the local variable title to the same String object.

The line name.replace("Sam") modifies the object. It doesn't matter which variable you used to access the object in the first place. title.replace("Sam") would have identical results, since it refers to the same object.