Learn to Code via Tutorials on Repl.it!

← Back to all posts
♦️ Basics of Ruby! ♦️
h
InvisibleOne (2935)

Ruby!

Ruby is a really cool and not that hard to learn language, it’s got a syntax sort of like a mix between Lua and Python but still unique and quirky. It’s fun to use and you can do a lot of really cool stuff in it.
First off, we have comments.
Comments, just like in python, can start with a # symbol. Like this

# This is a comment

But unlike python, we can also have multiline comments in ruby. These multiline comments start with =begin and end with =end

They look like this

=begin
this is a multiline comment
all these lines are comments
=end

In ruby, there are two ways to print something to a console. We can use print and puts
puts writes to the console and then makes a new line, while print doesn’t.
So if we did

puts "Hello, "
puts "World."

The console would print

Hello, 
World.

But if we did

print "Hello, "
print "World."

We would get

Hello, World.

In the console. Print is handy for things like prompts for getting input from the user and such.
Another note, you may sometimes see p putting things to the console, p works similar to puts, but puts whatever is in front of it, the differences look like this

puts "Hello World!" # We will see: Hello World! in the console
p "Hello World!" # We will see: "Hello World!" in the console

So don’t get them confused, puts is not the same as p

We can also add together strings

puts "Hello " + "World!" # Result: Hello World!

And we can add strings and numbers as well, as long as the numbers are converted to strings, which we can to be adding .to_s to the end of them (to string)

puts "The number is: " + 5.to_s

We can also put numbers inside of strings by using #{} like this

puts "The number is #{5.to_s}"

There are five main types of variables in Ruby, just like most other languages, they are integer, boolean, string, float, and list.
You don’t need to declare what type the variables are, Ruby automatically figures that out.

my_int = 20
my_float = 12.223
my_string = "Hello World!"
my_bool = true
my_list = [20, 12.233, "Hello World!", false]

Getting input from the user

Now that we have an idea of how to put stuff to the console, here’s how to get an input back from the user.
We use gets which gets the input from the user, and then chomp to chomp that input, it looks like this

name = gets.chomp

We can use print as a prompt since it won’t start a new line

print "What's your name: "
name = gets.chomp

Now you can use just plain gets you don’t need to chomp but if you don’t chomp it then it will also return the line break at the end, so you input will look something like “name\n” instead of just “name”

While loops

While loops work just like in python, you give it a argument and as long as that is true it will continue to do the code underneath it.
Just something to note with Ruby, you don’t put parenthesis around your arguments or use brackets like in some languages, and you don’t use : like in python. You simply leave nothing, and put the keyword end at the end of the block of code which the loop will execute

while true
	#code to execute
end

if, else, and elsif

If and else statements take a argument, and if the argument is true then they do the following code, end keywords are also put at the end of if/else statements.

if 1 == 1
	puts "1 is equal to 1"
else
	puts "Hmm, somethings up"
end

Notice that you don’t put the arguments inside of parenthesis and you also don’t use : or {}

elsif works almost the same

if 1 == 1
	puts "1 is equal to 1"
elsif 1 == 2
	puts "That's weird"
else
	puts "Hmmm"
end

Just always remember to put end at the end of any indented block of code.

Lists and Loops

You can do a lot of cool stuff in ruby with lists, and although it seems a little complicated at first, it’s not that hard and easier then other languages.

In other languages, such as python, we might do something like this

list = ['one', 'two', 'skip a few', 'ninety nine', 'onehundred']
for item in list:
	print(item)

Or in Javascript

const list = ['one', 'two', 'skip a few', 'ninety nine', 'onehundred'];
for (var i=0; i > 10; i++) {
  console.log(list[i]);
}

But in ruby we just use the .each operator (I think that’s what it’s called)
Which looks like this:

list = ['one', 'two', 'skip a few', 'ninety nine', 'onehundred']
list.each do |item|
	puts item
end

Let’s break this code down.
.each is used to reference each item in the list. do tells us what we are gong to do, and |item| inside of the vertical lines is what we are calling the items inside the list, this doesn’t have to be item, it can be whatever we want, its just a reference to the item in a list, this is often just i or n

Below that line we put what we want it to do with each item, which is put it to the console, and then we put end, to signify that we are ending our loop.

Times Loops

.times loop is a pretty cool loop we can use to do something a certain amount of times. And it looks like this

10.times do
	puts "This will be printed 10 times"
end

We just put the number we want, and then .times to signify that we are going to do the line of code below that many times.
We can also reference the number, by doing something like this

10.times do |i|
	puts "Number: #{i.to_s}"
end

This will result in 0-9 being printed out, because computers start with the number 0 and go up from there.
This can be a little bit annoying, so if we want it to go from 1 to 10 instead of 0 to 9, we need to do this

(1..10).each do |i|
	puts "Number: #{i.to_s}"
end

Hashes

Sort of like dictionaries in python, hashes in ruby store data with keys and values.
There are two ways to create a hash, we can create a hash be giving it values, or we can create a hash using Hash.new

Hash.new is for creating an empty dictionary, it looks like this

my_hash = Hash.new

Hashes have a default value, which is nil so if we try and reference a value with a key that does not exist in a hash, it will give us nil, unless we create a different default value. Maybe we want the default value to be Value not found we can put this as a default value in a hash by putting it inside parenthesis in the .new part of creating a hash, like this

my_hash = Hash.new("Value not found")
puts my_hash('key') # since 'key' doesn't exist as a key in the hash, it will give us "Value not found" when usually it would give us "nil"

When creating hashes in ruby, we can use strings as keys, using the rocket syntax, like this:

my_hash = {
	'key1' => "Key 1 value",
	'key2' => "Key 2 value",
}
puts my_hash['key1']

But in newer versions of ruby we use tokens instead of strings as key names because they are faster in processing.
A token starts with : and then has the name of the token, :token

We can use rocket syntax with tokens in ruby

my_hash = {
	:key1 => "Key 1 value",
	:key2 => "Key 2 value",
}
puts my_hash[:key1]

However in the newest versions of ruby, we don’t have to use rocket syntax anymore with tokens, instead of putting a rocket symbol => we put the : at the end of the token name and then the key value, just note that when referencing a key still put the : at the front of the token. It looks like this:

my_hash = {
	key1: "Key 1 value",
	key2: "Key 2 value",
}
puts my_hash[:key1]

Methods

Methods in ruby will remind a lot of people of python functions because they have a very similar syntax. A method starts with the keyword def short for define, and then the method name, and any arguments in parenthesis.
Underneath the method name and indented goes any code that will be completed when the method is called, and the method ends with the keyword end
Here’s an example of a simple method to add two numbers

def add(number1, number2)
	return number1 + number2
end

If there are no arguments for a method then we just put empty parenthesis ()

Other stuff

Well, that’s pretty much the basics of ruby (Although I’ve probably forgotten something)
But here’s some other random stuff that is good to know in ruby.

Clearing the screen

system('clear') # system('cls') if your on a windows computer

Using colors

require "colorize" # rubies version of import or include

puts "this is a cool green text".green
puts "This is a cool yellow text".yellow
puts "This is a cool red text".red
puts "We can also do black".black

Requiring other stuff

Just like in python there are hundreds of different packages to do pretty much whatever you want in ruby. You add them to your code by using require and then the name of the package in ””
But before you require something you have to make sure it’s added to your packages folder in your ruby files, to do this just type gem install package_name in the console.
On replit you need to go to packages on the left side of the screen and search for it, then press the plus to add it.

That’s pretty much all you need to know to get started with the basics of ruby.

Oh yeah, and just to show you the cool stuff you can do with ruby, below is a little password guesser I made, it's not exactly the fastest thing in the world, but it will eventually guess passwords.... eventually

Comments
hotnewtop
theangryepicbanana (1697)

There are five main types of variables in Ruby,

1) it might be worth capitalizing the type names, and renaming list to Array
2) I would also consider hashes and regexps to be main datatypes since they have literal syntax

You might also want to mention constants and case statements somewhere. Seems good otherwise

InvisibleOne (2935)

1, sorry it's a bad habbit of calling arrays lists
2. True, I didn't think about that
@theangryepicbanana

IntellectualGuy (819)

Nice tutorial, there have been many good tutorials these days, like @Kookiez Lua Tutorial, this tutorial, and My Python Tutorial 😏😏.

Th3Coder (129)

Wow, amazing tutorial! It's simple, easy to understand, and detailed! Thanks for teaching me :)

Btw, JavaScript uses console.log instead of print and you forgot the const keyword before the array...

Still, nice! Great job and thanks again! 😊

IOP3 (854)
Yes

now I know the basics of ruby :malicious
FlaminHotValdez (685)

Yayyy! Another detailed tutorial on a language that isn't Python!

IntellectualGuy (819)

There are multiline comments in python

'''
This
is
a
multiline
comment
in
python
'''
InvisibleOne (2935)

but those aren't really comments, just un assigned multi line strings. in ruby you have true multiline comments. @IntellectualGuy

Baconman321 (1097)

Ruby is weird :/

Nice tho!

InvisibleOne (2935)

Yeah it's a bit weird, but it's still fun to mess around with, I probably wouldn't use it for any real project I was working on, but I like to use it as a sort of hobby code @Baconman321