Chapter 3.7 Variables

Variables point a location in memory.

Example:

variable_1 = " This is a variable" 

--> This is a variable

variable_2 = variable_1

--> This is a variable

The chop! method deletes the last character of the string.

variable_2.chop!

--> This is a variabl

variable_1

--> This is a variabl

Variables are not objects but references to objects. References, however, do not hold actual objects but merely point to objects.

To duplicate an object, use the .clone or .dup method on objects.

Chaining assignment permits you to assign a value for lvalue and rvalue. Thus, lvalue is equal to rvalue.

Example:

left = 2 —> 2 left = middle = 4—> 4 left—> 4 middle—> 4

You can assign any array to a list of variables.

Example:

a, b = rvalue --> [1, 2, 3, 4]

a --> 1

b --> 2

The additive assignment operator (+=) operates in the same way as the (++) operator. The subtractive assignment operator (-=) operates in the same way as the -- operator.

Example:

red += 5 #red = red + 5 —> 5

blue += red #blue = blue + red —> 5

red -= blue #red = red – blue —> 0


  • Currently 3.04/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
  Flag Inappropriate Content 1 comments