Menu Close


Ruby: Variables

Variables are identifiers representing data elements. Every element have a data type that is automatically associated by Ruby using type inference. You can perform different operations on different data types using operators, functions and methods.


Ruby is a dynamic typed language. This thing is important and you have to learn how to live with it to avoid logical errors. Dynamic typing means you can change the variable content and type during program execution. This may be unintentional.  Usually is a bad practice to change data type of a variable and reuse variables for other purposes they are initially designed for.


I can change data type for a variable! Wait… what ?


  • variable names are simple identifiers starting with lowercase letters,
  • you can use string interpolation “#{}” to display nice messages,
  • later you can change a variable using a  new data type,
  • all variables in Ruby represent instances of specific classes.

Data Type

Ruby has built-in data types you can use to define variables and attributes.

  1. Numbers
  2. Strings
  3. Boolean
  4. Symbols
  5. Arrays
  6. Hashes


Literals are constants, created with alphanumeric symbols. Each data type has a specific literal notation that can be used to determine the type of variable. In Ruby you do not have to specify the type like you do in Java, C++ or Ada or Pascal. It is good enough to make an assignment using a literal.


In next example we use “assign operator” this will create an “assign statement”. 

Note: In Ruby there is no keyword for “assign” statement. You start with an “identifier” of a variable that may exist or not. If the variable do not exist it will be created immediate and will have an initial value equal to the expression literal.

Homework: Open this example live and run it: ruby data types


Ruby has two built-in collections. You can create a collection using type inference with literals like in Python. The two literals are using two kind of brackets: square brackets for Array and squiggly brackets for hash map:

  • [, , , ]  define one array
  • { , , , } define one hash map


Homework: Open this example live and run it: ruby collections


Operators are data type dependent. So for each data type you can have a different set of operators. The operators are actually functions with two parameters. Left operand and right operand. Each function can be “overloaded” using different parameter types. Do not wary if you do not understand this yet. Take a look at some operators and try to memorize them. I will use some of these operators in my next examples.

Numeric operators:

+Additionx+ySum of x and y.
Subtractionx-yDifference of x and y.
*Multiplicationx*yProduct of x and y.
/Divisionx/yQuotient of x and y.
%Modulusx%yRemainder of x divided by y.
**Exponentx**yx**y will give x to the power y

Numeric modifiers:

+=Add AND assignment operator.c += ac = c + a
-=Subtract AND assignment operator.c -= a c = c – a
*=Multiply AND assignment operator.c *= ac = c * a
/=Divide AND assignment operator.c /= ac = c / a
%=Modulus AND assignment operator.c %= ac = c % a
**=Exponent AND assignment operator.c **= ac = c ** a

Logical operators

In computer science, logical values are also known as Boolean values. These values are in Ruby lowercase: { true, false }.  In Python these values are uppercase {True, False}. Interesting fact that rue is instance of a special class: TrueClass while false is an instance of FalseClass. 

Several operators have a Boolean result. These operators can be “comparison operators”, “Boolean operators” and “relation operators”. Together they are called “logical operators” in this tutorial since they all produce true or false result.

Comparison operators

Sometimes comparison operators are also called relation operators. They are used to compare two numeric values. Also they can be used with strings. You should know the letter in the alphabet are ordered. Actually all symbols are ordered in ASCII order. So you can compare 1 with a for example.


In next example, we use operators: { < , >, <=, >=, ==, !=, <=>, ===}

Boolean operators

There are 3 Boolean operators you should be familiar with from CSE course. In Ruby you should use operators: { &&, ||, ! } for Boolean expressions. Alternative operators {and, or, not} are used only in special occasions.

Warning: Keywords {and, or, not} are available for used with “control flow” statements. Apparent the are the same, but the behavior is different due to operator precedence. “=” has higher precedence than these operators. This trick is used by Ruby programmers to create curious  statements. You will learn more about this later when you become more advanced.

The table of truth for Ruby operators:

AB!A!BA || BA && B

Boolean methods

In Ruby there is a curious notation for naming methods that return a boolean value. Method name is terminated with question mark. Such methods can be used in logical expressions.

  • eql? – compare value and type,
  • equal? – compare object id,
  • include? – verify if element belong to collection,
  • defined? – return nil if  the identifier is not defined.


Note: Sometimes a function can return nil value.This symbol signify “nothing”. In Python a similar value is “Null”. You can compare something with nil using “==” relation operator. 

Ternary operator

Question mark “?” can be used in expressions to select one alternative depending on result of a Boolean expression.  This is useful to create smarter expressions, for example let’s simulate absolute function using ternary expression.


Note:  We have used method: gets to read user input and method: to_i to convert a string into integer. We have not yet reach conversion operations. But this is a good moment to learn more about it.

Homework: run previous example twice using a positive and negative number: ternary operator


In Ruby you can not operate on different data types. There is a type safety built-in. However, some types are compatible and operator “==” is doing automatic conversion between float and integer type. Unlike JavaScript though you can not compare one string with one number.

Sometimes you must do explicit conversion between two data types. You can do this using “to_x” methods, where “x” can be “i”, “f”, “s” … depending on data type. For example let’s convert one number and concatenate the number with a string:


Note: In the previous example we use string interpolation as alternative. Sometimes you can do one thing in many ways in Ruby. It depends on every team to develop a style. You have to be prepared though to understand other’s code so we sometimes offer an alternative.

Read next: decision