TechLearn Hub

Learn Technology in Simple English

What Is Ruby? A Beginner's Guide to Ruby Programming

Welcome to this beginner-friendly Ruby tutorial. You will learn what Ruby is, how to write your first program, and how to work with variables, conditions, loops, methods, arrays, hashes, classes and objects. You will also discover Ruby on Rails, gems, databases and APIs.

Who is this guide for? This guide is for beginners. You can read the examples first, then practise them in a Ruby environment. You do not need to know Ruby before starting.

1. What Is Ruby?

Ruby is a high-level, general-purpose programming language known for its readable and expressive syntax. It was designed to help programmers write software in a way that is productive and enjoyable.

Ruby is used for web applications, automation, scripting, command-line programs, data processing and many other projects. It is especially well known for Ruby on Rails, a framework for building web applications.

Simple definition: Ruby is a programming language that lets developers write instructions for computers using a clear, expressive syntax.

2. Who Created Ruby?

Ruby was created by Yukihiro Matsumoto, commonly known as Matz. Its development began in Japan in the early 1990s. The language emphasizes programmer productivity, flexibility and readable code.

3. Why and Where Is Ruby Used?

Ruby can be used for many types of software, including:

4. How Does Ruby Work?

Ruby code is executed by a Ruby implementation. A typical workflow is:

  1. Write Ruby source code.
  2. Save the program in a file, such as hello.rb.
  3. Run the Ruby interpreter.
  4. Ruby processes the instructions.
  5. The program displays output or performs an action.

5. Your First Ruby Program

Here is a simple Ruby program:

puts "Hello, world!"

The puts method displays text and adds a newline after it.

6. Ruby Comments

Comments are notes for people reading the source code. Ruby uses # for single-line comments.

# This is a comment
puts "Hello"

7. Ruby Variables and Data Types

Variables hold references to values that a program can use. Ruby normally does not require you to declare a variable's type.

name = "Ahmed"
age = 20
height = 1.75
is_student = true

puts name
puts age
puts height
puts is_student
TypeExampleMeaning
String"Hello"Text
Integer25Whole number
Float25.5Decimal number
Booleantrue, falseTruth values
Array[1, 2, 3]Ordered collection
Hash{name: "Ahmed"}Key-value collection
Symbol:nameIdentifier commonly used as a key
NilnilRepresents no value

8. Strings and Numbers

Strings

Strings store text. Ruby supports string interpolation using #{...} inside double-quoted strings.

name = "Ahmed"
age = 20

puts "My name is #{name} and I am #{age} years old."

Numbers and Arithmetic

a = 10
b = 5

puts a + b
puts a - b
puts a * b
puts a / b
puts a % b
In Ruby, integer division such as 10 / 3 returns 3. Use 10.0 / 3 when you want a decimal result.

9. Ruby Operators

OperatorPurpose
+Addition
-Subtraction
*Multiplication
/Division
%Remainder
==Equality comparison
!=Inequality comparison
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to

10. If, Else, Elsif and Unless

Conditional statements let a program make decisions.

age = 20

if age >= 18
  puts "Adult"
else
  puts "Minor"
end

Using Elsif

score = 75

if score >= 80
  puts "Excellent"
elsif score >= 60
  puts "Good"
else
  puts "Keep practicing"
end

Using Unless

unless runs its body when the condition is false.

logged_in = false

unless logged_in
  puts "Please log in"
end

11. Ruby Loops

Loops repeat instructions. Ruby offers several ways to do this.

Times

5.times do
  puts "Hello"
end

Each

names = ["Ahmed", "Ali", "Umar"]

names.each do |name|
  puts name
end

While

i = 1

while i <= 5
  puts i
  i += 1
end

12. Ruby Methods

Methods are reusable blocks of code. They can receive arguments and return values.

def greet(name)
  puts "Hello #{name}"
end

greet("Ahmed")

Return Values

Ruby methods return the value of their last expression by default. The return keyword can also be used when needed.

def add(a, b)
  a + b
end

result = add(5, 3)
puts result

13. Ruby Arrays

Arrays store ordered collections of values. Array indexes begin at zero.

names = ["Ahmed", "Ali", "Umar"]

puts names[0]

names.push("Aisha")
puts names.length
puts names

Arrays can contain different kinds of objects, although keeping similar data together is often easier to maintain.

items = ["Phone", 100, true]

14. Ruby Hashes and Symbols

A hash stores values associated with keys. Symbols are often used as hash keys.

user = {
  name: "Ahmed",
  age: 20,
  country: "Nigeria"
}

puts user[:name]
puts user[:country]

15. Blocks and Iterators

A block is a section of code that can be passed to a method. Blocks are widely used with iterators such as each and times.

3.times do |number|
  puts number
end

numbers = [1, 2, 3, 4, 5]

numbers.each do |number|
  puts number
end

16. Classes, Objects and Instance Variables

A class defines behavior and structure. An object is an instance of a class. The initialize method runs when an object is created with .new.

class User
  def initialize(name)
    @name = name
  end

  def greet
    puts "Hello #{@name}"
  end
end

user = User.new("Ahmed")
user.greet

In this example, @name is an instance variable belonging to the object.

17. Inheritance and Modules

Inheritance

A class can inherit behavior from another class.

class Animal
  def speak
    puts "Animal sound"
  end
end

class Dog < Animal
  def bark
    puts "Woof"
  end
end

dog = Dog.new
dog.speak
dog.bark

Modules and Mixins

Modules help organize reusable code. Including a module in a class can add methods to that class; this is commonly called a mixin.

module Greetings
  def hello
    puts "Hello!"
  end
end

class User
  include Greetings
end

User.new.hello

18. Exception Handling

Exception handling lets a program respond to certain errors instead of stopping without an explanation.

begin
  number = Integer("not a number")
rescue ArgumentError
  puts "Please provide a valid number"
end
Prefer rescuing the specific exception you expect instead of catching every possible error without understanding it.

19. File Handling and User Input

Reading and Writing Files

File.write("notes.txt", "Hello from Ruby")

content = File.read("notes.txt")
puts content

File operations can fail because of permissions, missing files or storage problems, so production applications should handle relevant errors.

Reading Input from the Terminal

print "Enter your name: "

name = gets.chomp

puts "Hello #{name}"

20. Ruby Gems and Bundler

A Ruby gem is a packaged library or application. RubyGems is the package management system used to install and manage gems.

gem install example_gem

example_gem is a placeholder; replace it with the name of a real gem you want to install.

Bundler

Bundler manages project dependencies using a Gemfile.

source "https://rubygems.org"

gem "rails"

After creating a Gemfile, a project commonly uses bundle install to install its declared dependencies.

21. What Is Ruby on Rails?

Ruby on Rails, often called Rails, is a web application framework built with Ruby. It provides conventions and tools for developing database-driven applications.

Rails commonly provides routing, controllers, views, models, database integration and support for building web applications and APIs.

Understanding MVC

ComponentPurpose
ModelRepresents data and application rules.
ViewDisplays information to the user.
ControllerHandles requests and coordinates application behavior.

22. Ruby, Databases and APIs

Ruby applications can store and retrieve information from databases. Common choices include PostgreSQL, MySQL and SQLite. The right database depends on the application's needs.

Ruby can also create or consume APIs, allowing websites, mobile applications and other services to exchange data. JSON is a common format for structured API responses.

Working with JSON

require "json"

user = {
  name: "Ahmed",
  age: 20
}

json_data = JSON.generate(user)
puts json_data

23. Automation, Command-Line Tools and Testing

Ruby is useful for automating repetitive work, processing files, generating reports and building command-line programs.

Testing is also important. Ruby developers can use testing libraries and frameworks to check that methods and application features behave as expected.

Common tools in Ruby development include:

24. Ruby vs Python, JavaScript and PHP

LanguageCommon usesKey point
RubyWeb development, automation, scriptingKnown for expressive syntax and Rails
PythonAutomation, web development, data science, AIBroad ecosystem across many fields
JavaScriptBrowser applications and server-side developmentRuns in browsers and can also run on servers
PHPServer-side websites and web applicationsWidely used in web development

There is no single best language for every project. Consider your goals, the tools available, the project requirements and the ecosystem you want to learn.

25. Ruby Security Basics

Security matters in every application, especially when it handles user accounts, private data or payments.

Important: Never put passwords or private API keys directly into public source code or a public repository.

26. Ruby Learning Path

  1. Learn basic programming concepts.
  2. Install Ruby or choose a suitable Ruby learning environment.
  3. Practise variables, strings and numbers.
  4. Learn conditions and loops.
  5. Practise arrays and hashes.
  6. Write reusable methods.
  7. Understand blocks and iterators.
  8. Learn classes, objects, inheritance and modules.
  9. Practise exception and file handling.
  10. Learn RubyGems and Bundler.
  11. Understand HTTP, APIs and databases.
  12. Explore Ruby on Rails.
  13. Build and test small projects.

27. Beginner Ruby Project Ideas

Practising projects is one of the best ways to improve your programming skills. Start with a simple project and add features as you learn.

28. Common Ruby Mistakes

29. Ruby Cheat Sheet

ConceptExample
Printputs "Hello"
Variablename = "Ahmed"
Array[1, 2, 3]
Hash{name: "Ahmed"}
Conditionif age >= 18
Loop5.times do
Methoddef greet(name)
Classclass User
Create an objectUser.new("Ahmed")
Comment# This is a comment
Install a gemgem install GEM_NAME

30. Frequently Asked Questions

Is Ruby free?

Yes. Ruby is open-source software and can be used under its applicable license terms.

Is Ruby still used?

Yes. Ruby is still used for web applications, backend systems, automation, scripting and other software projects.

Can Ruby build websites?

Yes. Ruby can be used to build websites and web applications, particularly with frameworks such as Ruby on Rails.

Can Ruby build APIs?

Yes. Ruby can be used to build APIs and backend services that provide data to other applications.

Can Ruby connect to databases?

Yes. Ruby applications can work with databases through suitable libraries and frameworks.

Can Ruby build Android apps?

Ruby is not commonly used to build native Android interfaces directly. However, Ruby can power backend services that Android applications communicate with.

Is Ruby difficult to learn?

The basic syntax is readable, but advanced programming, databases, security and application architecture require time and practice.

What are Ruby gems?

Gems are packaged Ruby libraries or applications that developers can install and use in their projects.

What should I learn before Ruby on Rails?

Learn Ruby basics, methods, classes, arrays, hashes, HTTP, databases and basic web development. You can then move on to Rails and build practical projects.

31. Conclusion

Ruby is a readable and expressive programming language that can be used for web development, automation, scripting, APIs and many other software projects. Ruby on Rails is an important part of its web development ecosystem.

Start with variables, conditions, loops, methods, arrays and hashes. Then move on to classes, gems, databases, APIs and Rails as your confidence grows.

Your next step: Write a small Ruby program, run it, change the code and observe the result. Consistent practice will help you improve.

Back to top ↑