3.3 What Is a Variable?

A variable is a piece of data attached to a name. In algebra, a variable like x in the equation x = y + 2 indicates that x and y can take on many different values. In most programming languages, variables are defined just as in algebra and can be assigned different values at different times. In a computer, they refer to a location in memory. Although this is a simple concept, variables are the heart of almost every program you write. The Pythagorean theorem is shown in Figure 3-1, and it uses three variables: A, B, and C.

Pythagorean theorem
Figure 3-1. Pythagorean theorem

A, B, and C are the variable names, and they each represent a number. To create a variable in Ruby, simply use the format variable_name = value, where variable_name is the name of your variable and value is the value you would like it to have. The equal sign (=) behaves differently in Ruby from the way it does in algebra. In Ruby, = means “assign the RHS (righthand side) to the variables in the (LHS) lefthand side.” The code snippet y = x + 2 means compute the value of x + 2 and store the result into the variable y. In algebra, y = x + 2 simply explains a relationship between variables x and y.

An easy way to test things in Ruby is with irb (once Ruby is properly installed), the Interactive Ruby Shell. Enter irb from a command prompt; you can see that it is very easy to create variables. The following example ...

Get Computer Science Programming Basics in Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.