Getting Started With Variables

A variable is the same concept you might be familiar with from linear algebra x = 1 + 2 where you’d be asked to “solve for X”. In the context of a program, you can also think of them as containers, buckets, or a way of storing information that can be reused later in the program.

In many programming languages you’re required to define a “type” that the value of the variable must adhere to. In Ruby it’s much more simple. Here is a quick comparison between defining an integer variable in C++ vs. Ruby.

int a = 5;
cout << a;
a = 5
puts a

What happens if we wanted to store a non-integer value into the variable a?

int a = 5;
char a = "p";
cout << a;
a = 5
a = "p"
puts a

Hopefully you’ll see a pattern that Ruby is less strict about what goes into a variable than other languages like C++ or Java. Python is similar to Ruby in this and many other regards. The lesson to learn here is to be careful what you write because your program won’t alert you if you suddenly begin to store a string like "hello" where you’re expecting only numbers.