Ruby: Variables, Constants, and User Input

So by this point you should be able to output data to the screen (both numerical through mathematical expressions, and textual through the use of quotation marks) and save/run a basic Ruby file. But where can we go from here? Well the core concept that underpins most programs and scripts is that of the variable - and that's what this tutorial is all about.


A variable is basically just an empty box. We can put values into the box, see what's in the box, and also modify what's in the box. We use them for storing data that might change - perhaps the script is accepting some input from the user which could vary, or perhaps the script needs somewhere to store data that it uses internally. In Ruby, variables are type-less and dynamic. This means that we can put any kind of value we like into a variable - whether that value be a string (a series of characters - we talked about these in the last tutorial), a number, or something completely different. We can create variables in Ruby by simply typing whatever we want to call the variable, followed by an equals sign, followed by the value we want to set it to. The general naming convention (which is just a guideline for the most part and does not need to strictly be followed) for variables in Ruby is that they should be lowercase and that words should be separated by underscores. So if we wanted to create a variable called "user_name" (called declaring the variable) and set it to the value of "Joe" (the first setting of a variable is called initialising it), we might do something like the following:

1
user_name = "Joe"

We could then reference this variable at any point later in the program by simply writing user_name - this includes usage in puts and in mathematical expressions (although obviously trying to involve "Joe" in a mathematical expression isn't going to end well). We'll learn a bit more about variables and why they're so useful later in this tutorial, but for now let's take a quick tangent into constants. A constant is sort of like a variable (it's a 'box' that can hold a value), however it should only be set once - after which point its value should remain constant (hence its name). Constants are created in Ruby almost exactly like variables except the first letter should be an uppercase one. So if we wanted to create a constant called "Pi" and set it to the value of "3.141", we might do something like the following:

1
Pi = 3.141

Whenever we wanted to reference the number Pi in our program, we could simply write its name (with a capital 'P' of course) and 3.141 would be referenced. While we're on this tangent - any value that you write in Ruby which you've directly hard-coded in, such as "Hello World" or 3.141 is called a literal. This is just the name given to a fixed value.

But anyway, coming back from that tangent - although I've previously mentioned that all variables in Ruby are "type-less", this word could be rather misleading. Although variables aren't restricted to a certain type, they do have certain properties when holding certain values - you could argue that they do indeed have a type, one which is dynamic to the value assigned to it. But before we really get into different data-types a variable can store in Ruby, we should probably learn a little bit more about how variables work.

An object (in Object Oriented Programming) is something that belongs to a group (called a class) - everything inside this group can be treated in a similar manner. So to give an example, a program may have a class called 'Car' - various objects that stem from this root group would then be created, for example there may be objects like Bugatti_Veyron and Ferrari_458. These objects would share many similar properties and would contain similar data - perhaps data about speed, fuel, and looks in this case. Every variable in Ruby belongs to a class built into the language (like the groups we've just talked about) - these classes are dynamically changed depending on what type of data is being stored inside the variable. In fact, Ruby is a very object oriented language and so almost everything is an object - this is useful as it means everything has its own properties and actions, which we can use out of the box.

We can make use of the built in functionality of classes through the use of methods. These are pieces of code which are executed on objects and in Ruby are shown via a . after the object name, followed by the method name. So if we wanted to perform the method speed_up on the object Bugatti_Veyron in our pretend example, we would probably write something like Bugatti_Veyron.speed_up. All variables come with the preset method .class to find out the exact class they are in, let's test this out and learn about the basic data-types in Ruby.

The first data-type I want to cover is one we have already talked about - the string. It's just a mash-up of different characters, which is shown as a literal via the usage of double or single quotes (something like "Hello" or 'Hello'). Just to prove to you that the whole thing we just talked about with objects and variables taking on different classes isn't some elaborate lie - let's open up IRB and put this to the test. We can perform the .class method on literals too - so let's see what IRB evaluates the class of a given string to be:

1
2
ruby :001 > "Hello".class
 => String

Well what a surprise, it's determined that our string "Hello" is a member of the String class. The same would apply for using .class on a string variable:

1
2
3
4
ruby :001 > string = "Hello World!"
 => "Hello World!"
ruby :002 > string.class
 => String

So that's worth remembering (although let's be honest - it's difficult not to remember) - string variables always take on the String class. There are also some other cool things we can do with strings that I thought I'd talk about here - the first thing is escaping characters. So I'm not sure if you've thought of this already, but if we're using single quotes to represent a string literal - what do we do if we want to put an apostrophe somewhere inside of the string? Well luckily for us, it's very simple - we can tell Ruby that this apostrophe is just supposed to be in the string and is not supposed to end the literal by putting a backslash before it. Something like the following would work fine:

1
test_string = 'I\'m currently on holiday with the twins\' dog - it\'s truly amazing!'

Remember that we can define string literals with single or double quotes - sometimes it makes sense to choose which one to use depending on the contents of the string.

The other cool thing I wanted to talk about is called string interpolation. Before you start running away because it sounds a bit scary, let me just assure you it's much easier than it sounds. String interpolation basically just allows you to put variables (or any piece of Ruby code you like) inside of a string literal! It's accomplished through the use of #{ } inside a string and is extremely useful. Take the following for example:

1
2
3
4
5
6
7
Pi = 3.141

question_one_answer = "Pi is approximately #{Pi}"
question_two_answer = "Pi plus three is approximately #{ Pi+3 }"

puts question_one_answer
puts question_two_answer

We just put dynamic Ruby data directly into a string literal - how awesome is that? But aside from strings, there are obviously a bunch of other data-types - the first other types that come to mind are the different types of numbers.

Numbers in Ruby are represented in different classes depending on what kind of numbers they are. There are three main classes for numbers in Ruby that we'll be dealing with:

  • Fixnum - Whole numbers of a reasonable size
  • Bignum - Whole numbers of a large size
  • Float - Numbers with decimal places

The best way to learn about these classes is to try them out yourself. Try using .class on some literal numbers in IRB (and remember, literal numbers are just written by writing the numbers themselves) and see what class is returned. Take a look at the following results, which were returned from my machine:

1
2
3
4
5
6
ruby :001 > 10000000000000000000.class
 => Bignum
ruby :002 > 1.class
 => Fixnum
ruby :003 > 3.141.class
 => Float

As you can see, the results are exactly as I implied. While we're talking about numbers here, there are also four really useful operators for mathematics that add, minus, multiply, or divide a number (or variable which contains numerical data). Instead of having to write something like count = count + 5, which would work fine however is a little bit repetitive, we can simply use the += operator - so something like count += 5. These operators are fairly straightforward and are super useful:

  • += - Add to
  • -= - Minus from
  • *= - Multiply by
  • /= - Divide by

So now we have numbers and strings under our belt - what other data-types can there be? Well, quite a few actually - we'll just go through a couple more in this tutorial.

One of the important ones is the symbol. Symbols are basically just lightweight constant strings and are used when you want to repeat a word over and over again without using a lot of memory by storing the string in memory each time. They make a lot more sense when used with hashes (which we'll learn about in a tutorial soon), but for now let's just use them as short strings - so something like this would work fine:

1
puts :Hello

Wasn't that simple? I know what you're thinking though - why not just use just use strings? Well for now, try not to worry too much - all will become clear when we learn about hashes.

The last three data-types we are going to cover in this tutorial are just little ones (although by no means are they less important). The first is nil which is an object of the NilClass class. It basically just means nothing, as can be illustrated by using the to_i method (which converts things to integers (whole numbers)) on it:

1
2
3
4
ruby :001 > nil.class
 => NilClass
ruby :002 > nil.to_i
 => 0

You'll probably run into nil as you try things out later on in your Ruby career, although for now I can see why it would seem useless.

The last two data-types we are covering in this tutorial are those of true and false which belong to the TrueClass and FalseClass as appropriate. These are used to create the equivalent to basic boolean variables (if you've done any other programming these should be familiar) which can be set to a value of true or false - these are extremely useful, and the literals are written simply as the keywords themselves.

So let's go ahead and combine our elite knowledge of data-types (although admittedly we're missing a few which we'll cover in a tutorial soon) with some user input! It's extremely easy to get some text from the user in Ruby using gets. We can simply set a variable to gets and Ruby will prompt the user for some input when that variable assignment is reached at runtime. It's worth noting that the value received is always a string. The string received also has a newline (denoted by '\n' at the end) by default - we can remove this newline by using the .chomp method on gets (I told you everything in Ruby was an object!).

So let's just create a basic Ruby file (all string based since we don't really know about conversion yet), which asks the user for their name and then says "Hi" to them - if you don't understand any of the code below, try re-reading some parts of the tutorial (we've covered it all!). While we're creating the code, it's worth commenting it too just in-case we forget what it does. Comments are notes written in pieces of code which are meant for the developer(s) and do not actually add/remove any functionality -- single-line comments are expressed in Ruby via the hash symbol (#) - anything after a hash symbol on the same line will be ignored by the interpreter.

1
2
3
puts "Enter your name below..." #Prompt the user for their name
name = gets.chomp #Get the user's name
puts "Hello #{name}!" #Output the user's name

And there we go - you should now know all about a bunch of different data-types and all about getting input from the user (all this stuff is going to be extremely important later on in the course)!