Back-end · formation gratuite

Ruby Training

Learn Ruby and Ruby on Rails

  • Intermédiaire
  • 12 chapitres
  • Exemples de code
  • 100 % gratuit
Commencer le cours

Introduction to Ruby

Ruby is a dynamic, object-oriented, and interpreted programming language created by Yukihiro Matsumoto in 1995. Ruby is known for its elegant syntax and "programming for pleasure" philosophy.

💎 What is Ruby?

Ruby is an interpreted, object-oriented, and dynamically typed programming language. Ruby prioritizes simplicity and developer productivity.

💡 Why is Ruby so popular?

  1. Elegant syntax - Readable and expressive code, "programming for pleasure"
  2. Ruby on Rails - Powerful and productive web framework
  3. Productivity - Rapid web application development
  4. Community - Active and welcoming community
  5. Open-source - Free, cross-platform
  6. Flexibility - Very flexible, multiple ways to do things

🚀 Why learn Ruby?

Ruby is an excellent choice for rapid web development:

  • ✅ Ruby on Rails - Most productive web framework, used by GitHub, Shopify, Airbnb
  • ✅ Elegant syntax - Readable and expressive code, easy to maintain
  • ✅ Productivity - Rapid development, convention over configuration
  • ✅ High demand - Used by many startups and companies
  • ✅ Community - Active community, many gems (libraries)
  • ✅ Startups - Perfect for prototypes and rapid MVPs

📋 Prerequisites to learn Ruby

To learn Ruby effectively, it is recommended to have:

  • ✅ Programming basics - Understanding basic concepts (variables, conditions, loops)
  • ✅ Logic - Good understanding of programming logic

💡 Important note: To run Ruby code, you need Ruby. Install it from ruby-lang.org. You can use VS Code with the Ruby extension, or RubyMine (JetBrains IDE).

🎯 Ruby Use Cases

Ruby is used in many fields:

  • Web development - Ruby on Rails to create complete web applications
  • Scripts - Automation, system scripts, data processing
  • Prototypes - Rapid prototype and MVP development
  • E-commerce - Shopify (built with Ruby), e-commerce applications
  • APIs - REST API development with Rails

📝 Basic Syntax

Ruby syntax is elegant and expressive. Ruby often uses English keywords and supports multiple ways to write the same thing.

# Premier programme Ruby
puts "Bonjour, monde !"

nom = "NiangProgrammeur"
age = 25

# Interpolation avec #{...} (guillemets doubles)
puts "Je m'appelle #{nom} et j'ai #{age} ans"

💡 Important points about Ruby syntax:

  • Ruby is flexible - Multiple ways to write the same thing
  • Comments use # for a line or =begin =end for multiple lines
  • No semicolon needed - Line breaks are sufficient
  • Parentheses are optional - puts "Hello" or puts("Hello")
  • Methods - Everything is an object, even numbers
  • Conventions - Use snake_case for variables and methods

🔍 Detailed syntax example

Here is a complete example showing several aspects of Ruby syntax:

# Définition d'une méthode
def saluer(nom)
  "Bonjour, #{nom} !"   # la dernière expression est renvoyée
end

puts saluer("Awa")      # Bonjour, Awa !

# Les parenthèses sont facultatives
puts saluer "Moussa"

# Un bloc : du code passé à une méthode
3.times { |i| puts "Tour #{i + 1}" }

🔤 Variables

In Ruby, variables are created simply by assigning them a value. Ruby is a dynamically typed language, the type is determined at runtime.

# Déclaration de variables (aucun type à écrire)
nom = "Ruby"            # String
age = 30                # Integer
prix = 19.99            # Float
est_actif = true        # true / false
valeur_nulle = nil      # absence de valeur

# Affectation multiple
x, y, z = 1, 2, 3

# Constante : commence par une majuscule
PI = 3.14159

# Typage dynamique : la variable peut changer de type
valeur = 42
valeur = "quarante-deux"

# Connaître la classe d'un objet
puts age.class          # Integer
puts prix.class         # Float
puts valeur_nulle.nil?  # true

📌 Rules for variable names:

  • Must start with a letter or underscore _
  • Can contain letters, numbers, and underscores
  • Case sensitive
  • Cannot be Ruby keywords
  • Convention: use snake_case for variables

📊 Data Types

Ruby has several built-in data types. Here are the main ones:

# En Ruby, tout est un objet
entier = 42
decimal = 3.14
texte = "Bonjour"
symbole = :actif          # identifiant léger et unique
booleen = true

puts entier.even?         # true
puts texte.upcase         # BONJOUR
puts texte.length         # 7

# Tableau (Array)
langages = ["Ruby", "Python", "PHP"]
langages << "Go"          # ajout à la fin
puts langages.first       # Ruby
puts langages.size        # 4

# Hash (dictionnaire clé → valeur)
ages = { "Awa" => 20, "Moussa" => 22 }
etudiant = { nom: "Fatou", age: 19 }   # clés symboles
puts ages["Awa"]          # 20
puts etudiant[:nom]       # Fatou

# Intervalle (Range)
(1..5).each { |n| print n, " " }  # 1 2 3 4 5

📚 Ruby Data Types:

  • String - Character strings
  • Integer, Float - Integers and decimals
  • Boolean - Booleans (true/false, nil)
  • Array - Arrays
  • Hash - Dictionaries (key-value)
  • Symbol - Symbols (immutable identifiers)
  • Range - Value ranges

🔢 Operators

Ruby supports arithmetic, comparison, logical, and assignment operators:

a, b = 17, 5

# Opérateurs arithmétiques
puts a + b      # 22
puts a - b      # 12
puts a * b      # 85
puts a / b      # 3 (division entière entre Integer)
puts a % b      # 2 (reste)
puts a ** 2     # 289 (puissance)
puts a.to_f / b # 3.4

# Opérateurs de comparaison
puts a == b     # false
puts a != b     # true
puts a > b      # true
puts a <=> b    # 1 (« vaisseau spatial » : -1, 0 ou 1)

# Opérateurs logiques
majeur, inscrit = true, false
puts majeur && inscrit  # false
puts majeur || inscrit  # true
puts !majeur            # false

# Affectation combinée
total = 10
total += 5      # 15
total *= 2      # 30
total ||= 100   # garde 30 (n'affecte que si nil ou false)
puts total

🔀 Conditional Structures

Ruby uses if, elsif, and else for conditions. Ruby also supports unless (inverse of if) and case.

note = 14

# if / elsif / else
if note >= 16
  puts "Très bien"
elsif note >= 10
  puts "Admis"
else
  puts "Ajourné"
end

# unless : l'inverse de if
unless note < 10
  puts "Vous passez à l'année suivante"
end

# Condition en fin de ligne (très lisible)
puts "Mention bien" if note >= 14

# Opérateur ternaire
statut = note >= 10 ? "admis" : "ajourné"
puts statut

# case / when (avec intervalles)
case note
when 16..20 then puts "Très bien"
when 12...16 then puts "Bien"
when 10...12 then puts "Passable"
else puts "Insuffisant"
end

🔄 Loops

Ruby offers several types of loops: while, until, for, and methods like each, times:

# each : la manière idiomatique de parcourir
langages = ["Ruby", "Python", "PHP"]
langages.each { |langage| puts langage }

# each_with_index : valeur et position
langages.each_with_index do |langage, i|
  puts "#{i + 1}. #{langage}"
end

# times et upto
3.times { |i| puts "Tour #{i}" }
1.upto(5) { |n| print n, " " }
puts

# while et until
compteur = 3
while compteur > 0
  puts "Compte à rebours : #{compteur}"
  compteur -= 1
end

# Parcourir un hash
ages = { "Awa" => 20, "Moussa" => 22 }
ages.each { |nom, age| puts "#{nom} a #{age} ans" }

# next et break
(1..10).each do |n|
  next if n.even?   # ignore les pairs
  break if n > 7    # arrête la boucle
  puts n            # 1 3 5 7
end

# map, select, reduce : transformer des collections
carres = [1, 2, 3].map { |n| n * n }        # [1, 4, 9]
pairs  = (1..10).select(&:even?)            # [2, 4, 6, 8, 10]
total  = [1, 2, 3, 4].reduce(0) { |s, n| s + n }  # 10

⚙️ Methods

In Ruby, we speak of methods rather than functions. Methods are defined with def. Everything is an object in Ruby.

# Méthode simple
def bienvenue
  puts "Bienvenue sur NiangProgrammeur"
end

# Paramètres avec valeur par défaut
def saluer(nom, moment = "jour")
  "Bon#{moment} #{nom} !"
end

puts saluer("Awa")            # Bonjour Awa !
puts saluer("Awa", "soir")    # Bonsoir Awa !

# Paramètres nommés (keyword arguments)
def creer_compte(nom:, role: "élève")
  "#{nom} (#{role})"
end
puts creer_compte(nom: "Moussa", role: "professeur")

# Nombre d'arguments variable
def somme(*nombres)
  nombres.sum
end
puts somme(1, 2, 3, 4)        # 10

# Méthode qui reçoit un bloc
def deux_fois
  yield
  yield
end
deux_fois { puts "Bonjour" }

# Convention : ? pour une question, ! pour une méthode qui modifie
texte = "dakar"
puts texte.empty?             # false
texte.upcase!                 # modifie texte en place
puts texte                    # DAKAR

📋 Classes & Objects

Ruby is a pure object-oriented language. Everything is an object, even numbers and strings. Classes are defined with <code>class</code>.

class Etudiant
  # Génère les accesseurs nom, age et le mutateur notes
  attr_reader :nom, :age
  attr_accessor :notes

  def initialize(nom, age)
    @nom = nom          # variable d'instance
    @age = age
    @notes = []
  end

  def ajouter_note(note)
    @notes << note
    self                # permet d'enchaîner les appels
  end

  def moyenne
    return 0 if @notes.empty?
    @notes.sum.to_f / @notes.size
  end

  def to_s
    "#{@nom} (#{@age} ans) : #{moyenne.round(1)} de moyenne"
  end
end

awa = Etudiant.new("Awa", 20)
awa.ajouter_note(14).ajouter_note(16)
puts awa                # Awa (20 ans) : 15.0 de moyenne

# Héritage
class Delegue < Etudiant
  def to_s
    super + " · délégué de classe"
  end
end

puts Delegue.new("Moussa", 21)

📦 Modules

Modules allow grouping methods and constants. Modules can be included in classes (mixins) or used as namespaces.

# Un module regroupe des méthodes et des constantes
module Outils
  TVA = 0.18

  def self.prix_ttc(prix_ht)
    (prix_ht * (1 + TVA)).round
  end
end

puts Outils.prix_ttc(10_000)   # 11800
puts Outils::TVA               # 0.18

# Mixin : partager un comportement entre plusieurs classes
module Presentable
  def presenter
    "Je suis #{nom}"
  end
end

class Etudiant
  include Presentable
  attr_reader :nom
  def initialize(nom) = @nom = nom
end

class Formateur
  include Presentable
  attr_reader :nom
  def initialize(nom) = @nom = nom
end

puts Etudiant.new("Awa").presenter      # Je suis Awa
puts Formateur.new("Bassirou").presenter

# Charger la bibliothèque standard ou une gemme
require "json"
puts({ langage: "Ruby" }.to_json)       # {"langage":"Ruby"}

🏗️ Ruby on Rails

Ruby on Rails is a powerful web framework that follows the "Convention over Configuration" principle. Rails allows rapid web application development.

# Dans le terminal : créer et lancer une application Rails
# gem install rails
# rails new boutique
# cd boutique
# rails generate model Produit nom:string prix:integer
# rails db:migrate
# rails server            (http://localhost:3000)

# app/models/produit.rb : le modèle (Active Record)
class Produit < ApplicationRecord
  validates :nom, presence: true
  validates :prix, numericality: { greater_than: 0 }
end

# config/routes.rb : les routes
Rails.application.routes.draw do
  resources :produits     # crée les 7 routes CRUD
end

# app/controllers/produits_controller.rb : le contrôleur
class ProduitsController < ApplicationController
  def index
    @produits = Produit.order(:nom)
  end

  def create
    @produit = Produit.new(params.require(:produit).permit(:nom, :prix))
    if @produit.save
      redirect_to produits_path, notice: "Produit ajouté"
    else
      render :new, status: :unprocessable_entity
    end
  end
end

# Requêtes Active Record (sans écrire de SQL)
Produit.where("prix < ?", 5000).count

📁 File Manipulation

Ruby allows reading and writing files easily with the File class.

# Écrire dans un fichier (le crée ou l'écrase)
File.write("notes.txt", "Awa : 15\nMoussa : 12\n")

# Ajouter du texte à la fin (mode "a" = append)
File.open("notes.txt", "a") do |fichier|
  fichier.puts "Fatou : 17"
end   # le fichier est fermé automatiquement à la fin du bloc

# Lire tout le contenu
contenu = File.read("notes.txt")
puts contenu

# Lire ligne par ligne
File.foreach("notes.txt") do |ligne|
  nom, note = ligne.chomp.split(" : ")
  puts "#{nom} a obtenu #{note}/20"
end

# Lire toutes les lignes dans un tableau
lignes = File.readlines("notes.txt", chomp: true)
puts "#{lignes.size} élèves"

# Vérifier avant de lire
if File.exist?("notes.txt")
  puts "Taille : #{File.size('notes.txt')} octets"
end

# Gérer une erreur
begin
  File.read("absent.txt")
rescue Errno::ENOENT => e
  puts "Fichier introuvable : #{e.message}"
end

💡 Best practice: Use File.open with a block to guarantee automatic file closure.

🎓 Next Steps

Congratulations! You now have a solid foundation in Ruby.

✅ What you have learned:

  • Ruby syntax and variables
  • Data types (String, Integer, Array, Hash)
  • Operators and expressions
  • Conditional structures (if, case)
  • Loops (while, for, each)
  • Methods and blocks
  • Classes and objects
  • Modules and mixins
  • Ruby on Rails
  • File manipulation

🚀 To go further:

  • Ruby on Rails - Models, views, controllers
  • ActiveRecord - Rails ORM for databases
  • Routes - Rails routing system
  • Gems - Using and creating gems
  • Tests - RSpec, Minitest to test your code
Cliquer pour discuter avec NiangProgrammeur
NiangProgrammeur
En ligne

Bonjour ! 👋

Comment puis-je vous aider aujourd'hui ?