DEV Community

Cover image for Ruby Tutorial: Learn Ruby from scratch
Erin Schaffer for Educative

Posted on • Originally published at educative.io

Ruby Tutorial: Learn Ruby from scratch

Ruby is a popular open-source programming language mainly used for web development. Many big tech companies, like Airbnb, Twitter, and GitHub, are built on Ruby. A lot of Ruby's popularity comes from Ruby on Rails, which is a full-stack web application framework that runs Ruby.

The Ruby job market continues to grow, so learning Ruby will open up doors for you in your career. Today, we’ll dive deeper into the basics of the Ruby programming language and discuss syntax, key concepts, and more.

This tutorial will cover:

What is Ruby?

Ruby is an open-source, object-oriented programming language mainly used for web development. It was created in 1995 by Yukihiro Matsumoto, who wanted to create a scripting language stronger than Perl and more object-oriented than Python. He wanted something easy-to-use, functional, and dynamic.

Ruby is known for its simple syntax, making it easier to learn and understand. It has exception handling features like Java and Python, so it handles errors well. It’s also portable, working on various operating systems.

There’s also Ruby on Rails, which is an open-source web application development framework written in Ruby. With Ruby on Rails, it’s easy to build powerful web applications quickly because of its innovative features, like table migrations and scaffolds. Some of the largest websites run Ruby on Rails, including Airbnb, GitHub, Twitch, Twitter, and many more.

Why learn Ruby?

Let’s take a look at some of the perks of Ruby:

  • Fun and easy to learn: Ruby was designed to be fun to use and easy to learn. It was first used in Japan for making games. Ruby is concise and direct, reading much like the English language. This means it’s a great programming language for beginners.

  • Flexible: Ruby is dynamic and flexible. You’re not restricted by strict rules.

  • Object-oriented: In Ruby, everything is treated as an object. This means that every piece of code can have its own properties and actions.

  • Simple syntax: Ruby’s syntax is easy to learn, read, write, and maintain.

  • Vibrant community: Ruby has many loyal users and a large, active community.

Let’s get started learning Ruby and learn how to write a Hello World!.

Hello World in Ruby

The best way to learn Ruby is to get some hands-on practice. An easy way to get started working with the language is to use Interactive Ruby (IRB). IRB is a REPL that launches from a command line, allowing you to immediately execute and experiment with Ruby commands.

Now, let’s take a look at how to print a Hello World! in Ruby using IRB. The way you access IRB is different depending on your operating system.

  • If you’re using macOS, open up Terminal, type irb, and press enter.
  • If you’re using Windows, ensure you have an environment installed, and then open it up.
  • If you’re using Linux, open up a shell, type irb, and press enter.
puts "Hello World!"
Enter fullscreen mode Exit fullscreen mode

Output: Hello World!

Note: puts is similar to print in other languages.

Ruby syntax basics

Let’s take a look at some of the fundamental pieces of Ruby programs and how to implement them.

Variables

In Ruby, we use variables to assign labels to objects in our program. You can assign a label to an object by using the assignment operator =, like this:

amount = 5
puts amount
Enter fullscreen mode Exit fullscreen mode

Output: 5

In the above example, we assigned the label amount to the object, which is the integer 5. Then, we used puts to print our variable. It’s important to remember that a variable is not an object itself, it’s just a label or name for an object.

Note: The name on the left side of the assignment operator (=) is the name assigned to the object on the right side of the assignment operator.

Types of variables and their usage

Alt Text

Data types

In Ruby, data types represent different categories of data, like string, numbers, text, etc. Since Ruby is object-oriented, its supported data types are implemented as classes. Let’s take a look at the various data types in Ruby.

Strings

Strings are made up of characters. You define them by enclosing characters within single ’string’ or double ”string” quotes. In the below code, both strings function the same way:

puts "Hello World!"
puts 'Hello World!'
Enter fullscreen mode Exit fullscreen mode

Numbers

Integers and floats are two main kinds of numbers that Ruby can handle. An integer is a number without a decimal point, and a float is a number with a decimal point. You use floats when you need to be more precise. Here’s an example of both:

our_integer = 17
our_float = 17.17
Enter fullscreen mode Exit fullscreen mode

Booleans

A boolean is a data type with two possible values: true or false. You use them in logic statements. They’re helpful when you want to make decisions. Let’s look at an example:

our_string_1 = "Dog"
our_string_2 = "Cat"

if our_string_1 == our_string_2
  puts "True!"
else
  puts "False!"
end
Enter fullscreen mode Exit fullscreen mode

Output: False!

Let’s break down the code:

  • We start by defining two variables: my_string_1, which is assigned to the string ”Dog”, and my_string_2, which is assigned to the string ”Cat”.

  • We use an if statement to test whether our two variables are equal to one another. If they’re equal, our output is ”True!”. If they aren’t equal, our output is ”False!”.

  • end closes the if statement, which means any code you write after will not be part of your if statement block.

  • Since ”Dog” is not equal to ”Cat”, our variables are not equal. The output will be False!.

Arrays

Arrays are data structures that can store multiple items of different data types. For example, an array can store both strings and integers. Items in an array are separated by commas and enclosed within square brackets [X, Y, Z]. The first item in an array has an index of 0. Let’s look at an example:

our_array = ["chocolate", 1.234, false, "Pancakes", 45]

# Printing the elements of our array

our_array.each do |x|
  puts(x)
end
Enter fullscreen mode Exit fullscreen mode

Output:
chocolate
1.234
false
Pancakes
45

Let’s break down the code:

  • In our array, we store two strings, one float, one boolean, and one integer. We create a variable name our_array for the array, and use the square brackets around the first and last items.

  • We then use the # sign to make a comment about what the next step in our code is, which is printing all the elements of our array.

  • We use the each method to tell Ruby to iterate through each element in our array and print them out.

Symbols

Symbols are like lighter versions of strings. They are preceded by a colon :. You use them instead of strings when you want to take up less memory space and have better performance. Let’s take a look:

our_symbols = {:bl => "blue", :or => "orange", :gr => "green"}

puts our_symbols[:bl]
puts our_symbols[:or]
puts our_symbols[:gr]
Enter fullscreen mode Exit fullscreen mode

Output:
blue
orange
green

Let’s break down the code:

  • We start by defining our symbols and assigning our strings to their respective symbols.

  • We use puts to print our symbols, which return as the strings they’re assigned to.

Comments

Ruby comments begin with the # symbol and end at the end of the line. Any characters within the line that are after the # symbol are ignored by the Ruby interpreter.

Note: Your comments don’t have to appear at the beginning of a line. They can occur anywhere.

Let’s take a look at a comment in Ruby:

puts "Hello World!" # Printing a Hello World

# Now I want to print my name

puts "Erin"
Enter fullscreen mode Exit fullscreen mode

Output:
Hello World!
Erin

If you run the code, you see that the comments are ignored by the interpreter, and your output only includes the two puts statements.

Functions

In Ruby, functions are declared using the def keyword. The function syntax looks like this:

def ourfunction(variable)
  return <value>
end
Enter fullscreen mode Exit fullscreen mode

Ruby functions can accept parameters. Here’s how you can pass them:

def ourfunction(name)
  return "Hi, #{name}"
end 

ourfunction("Foo")
Enter fullscreen mode Exit fullscreen mode

When calling a function in Ruby, the parentheses are optional. We could also write the previous example like this:

def ourfunction(name)
  return "Hi, #{name}"
end 

ourfunction "Foo"
Enter fullscreen mode Exit fullscreen mode

Conditionals

When programming, we often want to check for a certain condition, and then based on that condition, perform one action or another. These are called conditionals. Let’s take a look at a conditional in Ruby:

number = 3

if number.between?(1, 5)
  puts "This number is between 1 and 5"
elsif number.between?(6, 10)
  puts "This number is between 6 and 10"
else
  puts "This number is greater than 10"
end
Enter fullscreen mode Exit fullscreen mode

Output: This number is between 1 and 5

Let’s break down the code:

  • This code will print out The number is between 1 and 5, because the number assigned to the variable number on the first line is 3. This means that the method call number.between?(1, 5) returns true.
  • Ruby will execute the code in the if branch and will ignore the rest of the statement.

Note: The elsif and else statements and branches are optional, but there must be an if statement and branch.

Now, we’re going to take a quick look at the shorthand syntax to write conditionals in Ruby.

Trailing if

We can append our if statement to the code on the if branch if it’s just on one line. So, instead of doing this:

number = 3

if number.odd?
  puts "This number is odd"
end
Enter fullscreen mode Exit fullscreen mode

We can instead do this:

number = 3
puts "The number is odd" if number.odd?
Enter fullscreen mode Exit fullscreen mode

This is a great example of the readable syntax of Ruby. Not only does the second example save us two lines, it reads very well!

unless

Ruby also has the unless statement, which we can use when we want to do something if the condition doesn’t apply (doesn’t evaluate to true). Again, we can append the unless statement to the end of the line. These two are the same:

number = 4

## First option

unless number.odd?
    puts "This number is not odd"
end 


# Second option

puts "This number is not odd" unless number.odd?
Enter fullscreen mode Exit fullscreen mode

Parentheses

In Ruby, when you define or execute a method, you can omit the parentheses. The following two lines of code mean exactly the same thing:

puts "Hi"
puts("Hi")
Enter fullscreen mode Exit fullscreen mode

Output:
Hi
Hi

So, when do I use parentheses and when do I omit them?

Great question! There’s actually no clear rule about this, but there are some conventions. Here’s what we recommend you stick with for now:

  • Use parentheses for all method calls that take arguments, except for puts, p, require, and include

  • If a method doesn’t take any arguments, don’t add empty parentheses, just omit them.

Key Ruby concepts

Let’s take a look at some key Ruby concepts.

Classes

In object-oriented programming, classes are like blueprints for creating objects and methods that relate to those objects. The objects are called instances. Let’s say we have a class called Color, and within it, we have the instances red, blue, green, and purple.

We define a class by using the keyword class and the keyword end:

class Color
end
Enter fullscreen mode Exit fullscreen mode

We use uppercase letters to name our classes, so instead of color, we use Color. For class names that consist of several words, we use *CamelCase*, with the first letter of each word being capitalized.

Objects

Since Ruby is object-oriented, we work with objects. We can think of objects as doing two things: objects know things, and objects can do things. For example, a string holds a group of characters, but it can also perform an action onto those characters. The str.reverse method returns a new string with the order of the string’s characters reversed:

color = "green"
color.reverse
puts color
Enter fullscreen mode Exit fullscreen mode

Output: green

Constants

A constant in Ruby is a type of variable. They always start with an uppercase letter and can only be defined outside of methods. We typically use them for values that aren’t supposed to change, but Ruby doesn’t stop you from changing them if you want. Let’s take a look at some valid Ruby constants:

Animals = "dog"
VEGETABLES = "carrot"
Abc = 3
Enter fullscreen mode Exit fullscreen mode

Operators

Ruby supports a large set of operators. Today, we’ll just take a look at the arithmetic operators and what they do.

Arithmetic operators

Alt Text

Built-in functions

Ruby has many built-in functions. Let’s take a look at some built-in functions and what they do.

Alt Text

What to learn next

If you want to learn Ruby online, there’s no better time to start than now. Ruby is an in-demand programming language, so becoming familiar with the language will help you build long-lasting skills for your career development. We’ve already covered some of the basics, but we’re only just getting started with our Ruby learning. Some recommended concepts to cover next are:

  • Hashes
  • The each and collect iterators
  • Modules
  • Etc.

To learn about these concepts and much more, check out Educative’s free course Learn Ruby from Scratch. This introductory Ruby course requires no prerequisites and provides you with hands-on practice with variables, built-in classes, conditionals, and much more. By the end of the course, you’ll know the basics of the most influential and demanding third-generation programming language.

Happy learning!

Continue reading about Ruby

Top comments (3)

Collapse
 
sakko profile image
SaKKo

I love Ruby. The most productive I ever get is with Ruby.

Collapse
 
kalebu profile image
Jordan Kalebu

I was actually thinking of learning ruby and thanks for this

Collapse
 
erineducative profile image
Erin Schaffer

Awesome! Glad you enjoyed the article, Jordan. :)