Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

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

Posted on • Originally published ateducative.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 anopen-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 itssimple syntax, making it easier to learn and understand. It has exception handling features like Java and Python, so ithandles errors well. It’s also portable, working on various operating systems.

There’s alsoRuby 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 aHello 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 aHello World! in Ruby using IRB. The way you access IRB is different depending on your operating system.

  • If you’re using macOS, open upTerminal, typeirb, 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, typeirb, and press enter.
puts "Hello World!"
Enter fullscreen modeExit fullscreen mode

Output:Hello World!

Note:puts is similar toprint 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, weuse 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 = 5puts amount
Enter fullscreen modeExit fullscreen mode

Output:5

In the above example, we assigned the labelamount to the object, which is the integer5. Then, we usedputs to print our variable. It’s important to remember thata 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 modeExit fullscreen mode

Numbers

Integers andfloats 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 = 17our_float = 17.17
Enter fullscreen modeExit fullscreen mode

Booleans

A boolean is a data type with two possible values:true orfalse. 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 modeExit 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”, andmy_string_2, which is assigned to the string”Cat”.

  • We use anif 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 theif statement, which means any code you write after will not be part of yourif statement block.

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

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 arrayour_array.each do |x|  puts(x)end
Enter fullscreen modeExit 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 nameour_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 theeach 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 theminstead 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 modeExit 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 useputs 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 nameputs "Erin"
Enter fullscreen modeExit 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 twoputs statements.

Functions

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

def ourfunction(variable)  return <value>end
Enter fullscreen modeExit 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 modeExit 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 modeExit 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 = 3if 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 modeExit fullscreen mode

Output:This number is between 1 and 5

Let’s break down the code:

  • This code will print outThe number is between 1 and 5, because the number assigned to the variablenumber on the first line is3. This means that the method callnumber.between?(1, 5) returnstrue.
  • Ruby will execute the code in theif branch and will ignore the rest of the statement.

Note: Theelsif andelse statements and branches are optional, but theremust be anif statement and branch.

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

Trailingif

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

number = 3if number.odd?  puts "This number is odd"end
Enter fullscreen modeExit fullscreen mode

We can instead do this:

number = 3puts "The number is odd" if number.odd?
Enter fullscreen modeExit 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 theunless statement, which we can use when we want to do something if the conditiondoesn’t apply (doesn’t evaluate to true). Again, we can append theunless statement to the end of the line. These two are the same:

number = 4## First optionunless number.odd?    puts "This number is not odd"end # Second optionputs "This number is not odd" unless number.odd?
Enter fullscreen modeExit 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 modeExit 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 forputs,p,require, andinclude

  • 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 somekey Ruby concepts.

Classes

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

We define a class by using the keywordclass and the keywordend:

class Colorend
Enter fullscreen modeExit fullscreen mode

We use uppercase letters to name our classes, so instead ofcolor, we useColor. Forclass 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. Thestr.reverse method returns a new string with the order of the string’s characters reversed:

color = "green"color.reverseputs color
Enter fullscreen modeExit fullscreen mode

Output:green

Constants

A constant in Ruby is a type of variable. Theyalways 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 modeExit 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
  • Theeach andcollect iterators
  • Modules
  • Etc.

To learn about these concepts and much more, check out Educative’s free courseLearn 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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
kalebu profile image
Jordan Kalebu
Python Developer | Machine Learning & AI Enthusiast | Mechatronics Engineer
  • Email
  • Location
    Dar es Salaam, Tanzania
  • Education
    Diploma in Mechatronics Engineering
  • Work
    Software Developer || AWS Architect
  • Joined

I was actually thinking of learning ruby and thanks for this

CollapseExpand
 
erineducative profile image
Erin Schaffer
B2C Technical Content Marketing / Blog Team Lead for Educative.io (she/her)Sign up for our blog newsletter here: https://www.educative.io/blog/blog-newsletter-annoucement
  • Location
    Bellevue, WA
  • Joined

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

CollapseExpand
 
sakko profile image
SaKKo
Geek is the new sexy.
  • Location
    Thailand
  • Education
    Mahidol University International College
  • Work
    CEO at Geekstart Company Limited
  • Joined

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

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Get hands-on with top tech skills. Level up your career.

Level up on in-demand tech skills - at your own speed.

Text-based courses with embedded coding environments help you learn without the fluff.

More fromEducative

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp