In this post we will setup our Ruby environment, then start printing out values to the console and will also be touching on variables.
I have a Docker image built on Alpine, the resources can be found via:
To setup a Ruby environment on your workstation, I would recommend using https://github.com/rbenv/rbenv.
Drop into a Ruby Shell:
I will be using Docker to drop into a ruby container:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
If you have the
irb output, you should be good to go.
Strings and Integers
You will find when you enter a string, which is represented as one or more characters enclosed within quotation marks:
The integers will be without the quotation marks, when we introduce anything within quotation marks, ruby will read it as a string. So for a integer, lets provide ruby with a number and the number will be returned to the shell:
Using mathematical symbols like the
+ will either sum the two values when they are integers, or concatenate when they are strings.
Let’s start with strings: we will add the string
Now let’s add two numbers together,
As you can see, it did a calculation on the two numbers as they were treated as integeres. But what happens when we add them as strings?
Adding them as strings, will concatenate them.
Ruby’s strings has many built in methods, which makes it convenient manipulating data, let me go through a couple that I am working with:
Getting the length of the string:
Is the string empty?
Getting the index position of 0 of the string:
Getting a array of your string:
Returning your string in Uppercase:
Returning your string in Lowercase:
Capitalize your String:
Swap the case of your string:
Let’s define variables to the static content that we used above.
Let’s define our key:
word to the value: of
Accessing the variables value:
We can also use
puts, which stands for
put string, which prints out the value to the terminal:
We can also, format our variable so that we can add something like a exclamation mark:
Let’s do the same with integers:
1 2 3 4
Now when we calculate the numbers using variables, you will find the expected result of 30:
1 2 3
Variables are Mutable:
Remember that variables are mutable, so they can be changed after they have been set, lets take age for example:
1 2 3 4 5 6 7
Strings and Integers:
What happens when we add strings and integers together in one line:
1 2 3 4 5 6 7 8 9 10
That is because we cant concatenate strings with integers, so we will need to convert the integer to a string, we do that with the
And if we want to define that to a variable:
1 2 3
Working with rb files:
We can add this together in a file with a
.rb extension and call the file as an argument with ruby, as a script:
Create the file, in my case
1 2 3 4 5
Running the ruby file: