0% found this document useful (0 votes)
42 views38 pages

Ruby: From Darkness To Dawn

Ruby is a high-level, interpreted programming language known for its simple syntax and object-oriented nature, created by Yukihiro Matsumoto. It is versatile, suitable for web development, automation, prototyping, and data processing. The document also covers installation, variable types, data types, conditional statements, loops, and functions in Ruby.

Uploaded by

Souhail Laghchim
Copyright
© Public Domain
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views38 pages

Ruby: From Darkness To Dawn

Ruby is a high-level, interpreted programming language known for its simple syntax and object-oriented nature, created by Yukihiro Matsumoto. It is versatile, suitable for web development, automation, prototyping, and data processing. The document also covers installation, variable types, data types, conditional statements, loops, and functions in Ruby.

Uploaded by

Souhail Laghchim
Copyright
© Public Domain
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

introduction to Ruby:

 What is Ruby?
Ruby is a high-level, interpreted programming language that is designed to be easy to read and
write. It was created by Yukihiro Matsumoto in the mid-1990s with the goal of making
programming more enjoyable.

 Simple and elegant syntax: Ruby is often compared to English.


 Object-oriented: Everything in Ruby is an object, even numbers and strings.
 Flexible: Ruby lets you modify and extend existing code easily.

 Where Can You Use Ruby?


Ruby is a general-purpose language, so you can use it for many things, including:

1. Web Development

 Ruby is best known for the Ruby on Rails framework (often just called Rails).
 Rails helps you build web apps quickly and cleanly.
 Big companies like GitHub, Shopify, and Airbnb started with Ruby on Rails.

2. Automation / Scripting

 Ruby is great for writing small scripts to automate tasks.

3. Prototyping

 Its clean syntax makes it easy to build a quick prototype or proof of concept.

4. Data Processing

 While not as common as Python, Ruby can be used for data work as well.
 How to Use Ruby
1. Install Ruby

 If you’re using Linux or macOS, Ruby is often pre-installed.


 You can also install it using:
o https://www.ruby-lang.org/
o Use a version manager like rbenv or RVM (recommended for developers).
 For windows:
https://rubyinstaller.org/

Choose the Right Version

 Pick the latest stable version (e.g., Ruby 3.2.x or Ruby 3.3.x).
 Use the "With Devkit" version. It includes tools for building native extensions (which
some gems need).

Example: Ruby+Devkit 3.2.2-1 (x64)


Complete MSYS2 Installation

After installation, a terminal will pop up asking you to install MSYS2. Choose option 3:

CMD:

 3. MSYS2 and MINGW development toolchain


Test Your Installation

Open Command Prompt and type:

CMD:

 ruby -v

You should see something like:

CMD:

 ruby 3.3.2p123 (2025-xx-xx revision xxxx) [x64-mingw-ucrt]

Also check:

CMD:

 irb

This opens the interactive Ruby shell.

2. Run Ruby Code

You can run Ruby in three main ways:

➤ IRB (Interactive Ruby Shell):

CMD:

 irb

This opens a terminal where you can type Ruby commands and get instant feedback.
➤ Ruby Script File:

Create a file like hello.rb and run:

Ruby:

 # hello.rb
 puts "Hello, world!"

Run it in the terminal:

CMD:

 ruby hello.rb
variables in Ruby:

 What is a Variable in Ruby?


A variable is a name that stores a value. In Ruby, you don't need to declare a variable type like
in some other languages. Ruby figures it out for you.

 Types of Variables in Ruby


Ruby has four types of variables:

1. Local Variables
2. Instance Variables
3. Class Variables
4. Global Variables

1. Local Variables

 Start with a lowercase letter or underscore (_).


 Only accessible within the block or method they are defined in.

Ruby:

 def say_hello
 name = "Ruby"
 puts "Hello, #{name}!"
 end
 say_hello
2. Instance Variables

 Start with @.
 Belong to a particular object (instance of a class).

Ruby:

 class Person
 def initialize(name)
 @name = name
 end

 def greet
 puts "Hi, I am #{@name}."
 End
 end

 person = Person.new("Souhail")
 person.greet

This Ruby code defines a Person class with two methods: an initialize method that sets the
person's name when a new object is created, and a greet method that prints a greeting including
that name. The code then creates a new Person object with the name "Souhail" and calls the greet
method, which will output "Hi, I am Souhail." to the console.RetryClaude can make mistakes.
Please double-check responses.
3. Class Variables

 Start with @@.


 Shared among all instances of a class.

Ruby:

 class Dog
 @@count = 0

 def initialize(name)
 @name = name
 @@count += 1
 end

 def self.total_dogs
 puts "Total dogs: #{@@count}"
 end
 end

 dog1 = Dog.new("Rex")
 dog2 = Dog.new("Buddy")
 Dog.total_dogs
4. Global Variables

 Start with $.
 Accessible from anywhere in the program.

Ruby:

 $greeting = "Hello, world!"

 def greet
 puts $greeting
 end

 greet
 Bonus: Constants
 Start with an uppercase letter.
 Used to store fixed values.

Ruby:

 PI = 3.14
 puts "The value of PI is #{PI}"
Data Types in Ruby:

 Ruby Data Types


Ruby is dynamically typed, which means you don’t have to specify a data type. It figures it out
automatically based on the value.

Here are the main data types in Ruby:

1. Integer

Used to represent whole numbers.

Ruby:

 age = 25
 puts age # Output: 25
 puts age.class # Output: Integer
2. Float

Used to represent numbers with decimals.

Ruby:

 price = 19.99
 puts price # Output: 19.99
 puts price.class # Output: Float

3. String

Used for text (characters inside quotes).

Ruby:

 name = "Ruby"
 puts name # Output: Ruby
 puts name.class # Output: String
4. Boolean

Two values only: true or false.

Ruby:

 is_ruby_fun = true
 puts is_ruby_fun # Output: true
 puts is_ruby_fun.class # Output: TrueClass

5. Nil

Represents "nothing" or "no value".

Ruby:

 nothing_here = nil
 puts nothing_here # Output:
 puts nothing_here.class # Output: NilClass
6. Array

Used to store a list of items.

Ruby:

 fruits = ["apple", "banana", "cherry"]


 puts fruits[0] # Output: apple
 puts fruits.class # Output: Array
7. Hash

Stores key-value pairs (like a dictionary).

Ruby:

 person = { "name" => "Shay", "age" => 19 }


 puts person["name"] # Output: Shay
 puts person.class # Output: Hash

Or using symbols as keys:

Ruby:

 person = { name: "Cormac", age: 19 }


 puts person[:name] # Output: Cormac
8. Symbol

Symbols are like lightweight strings, used as identifiers.

Ruby:

 language = :ruby
 puts language # Output: ruby
 puts language.class # Output: Symbol

9. Range

Represents a sequence of numbers or letters.

Ruby:

 numbers = (1..5)
 puts numbers.to_a # Output: [1, 2, 3, 4, 5]
 puts numbers.class # Output: Range
10. Object

Everything in Ruby is an object. Even numbers and strings!

Ruby:

 puts 5.class # Output: Integer


 puts "hi".class # Output: String

Conditional Statements in Ruby:

 What are Conditional Statements?


They check conditions (true/false) and run different code depending on the result.
 if Statement
Basic condition check.

Ruby:

 age = 18
 if age >= 18
 puts "You're an adult."
 end
 if...else
Handles two cases: if true, do one thing; if false, do another.

Ruby:

 temperature = 15
 if temperature > 20
 puts "It's warm."
 Else
 puts "It's cold."
 End

In Ruby, keywords like if, else, and end need to be lowercase. I also added some indentation to
make the code more readable, though that's not required for the code to run correctly.
 if...elsif...else
For multiple conditions.

Ruby:

 score = 85

 if score >= 90
 puts "Grade: A"
 elsif score >= 80
 puts "Grade: B"
 elsif score >= 70
 puts "Grade: C"
 else
 puts "Grade: F"
 end
 unless
The opposite of if. Runs code unless the condition is true.

Ruby:

 logged_in = false

 unless logged_in
 puts "Please log in."
 End

 One-line Conditionals
Short form if you have just one line of code:

Ruby:

 password = "your_input_here" # Define the password variable


 puts "Access granted!" if password == "secret"
 puts "Access denied!" unless password == "secret"
 Ternary Operator (? :)
A short way to write if...else in one line.

Ruby:

 age = 17
 puts age >= 18 ? "Adult" : "Minor"
 case Statement
Use when checking one variable against multiple values.

Ruby:

 day = "Monday"

 case day
 when "Monday"
 puts "Start of the week"
 when "Friday"
 puts "Weekend coming!"
 else
 puts "Just another day"
 end

Summary Table
Statement Description
if Run block if condition is true
if...else Run one block or another
elsif Check multiple conditions
unless Run block unless condition is true
case Clean way to check many values
? : Short if-else (ternary)
Loops in Ruby:

 What Are Loops?


Loops let you execute a block of code repeatedly as long as a condition is true or over a
collection (like arrays).

1. while Loop
Repeats while a condition is true.

Ruby:

 i = 1

 while i <= 5
 puts "Count: #{i}"
 i += 1
 end
 2. until Loop
Repeats until a condition becomes true (opposite of while).

Ruby:

 i = 1

 until i > 3
 puts "Number: #{i}"
 i += 1
 end

 3. for Loop
Iterates over a range or collection.

Ruby:

 for i in 1..3
 puts "Hello #{i}"
 end
 4.each Loop (Most Common in Ruby)
Used with arrays and hashes.

Ruby:

 fruits = ["apple", "banana", "cherry"]

 fruits.each do |fruit|
 puts "I like #{fruit}"
 end

 5.times Loop
Repeat a block n times.

Ruby:

 3.times do
 puts "Ruby is fun!"
 end
 6.break and next
break – Stops the loop early.
Ruby:

 i = 1

 while i <= 5
 break if i == 3
 puts i
 i += 1
 end
next – Skips to the next iteration.
Ruby:

(1..5).each do |i|
next if i == 3
puts i
end

 Summary Table
Loop Type Used For
while Looping with a condition
until Looping until a condition becomes true
for Looping over a range or array
.each Iterating over collections (array/hash)
.times Repeating fixed number of times
break Stop the loop
next Skip one iteration
Functions in Ruby:

 What is a Function (Method) in Ruby?


A function (or method) is a block of code that performs a specific task and can be called
multiple times.

 Define a Simple Method


Use the def keyword and end it with end.

Ruby:

 def greet
 puts "Hello from Ruby!"
 end

 greet
 Method with Parameters
You can pass values (arguments) to methods.

Ruby:

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

 greet("Developer!")

 Method with Multiple Parameters


Ruby:

 def add(a, b)
 sum = a + b
 puts "Sum is #{sum}"
 end

 add(5, 3)
 Returning a Value
Use return to send a value back.

Ruby:

 def square(x)
 return x * x
 end

 result = square(4)

 puts result

➡️ Note: Ruby automatically returns the last line, so return is optional.

Ruby:

 def cube(x)
 x * x * x # This line is returned
 end

 puts cube(3)
 Default Parameters
Provide default values if no arguments are passed.

Ruby:

 def greet(name = "Guest")


 puts "Welcome, #{name}!"
 end

 greet("Ruby") # Output: Welcome, Ruby!


 greet # Output: Welcome, Guest!
 Variable Number of Arguments (*args)
Use * to accept many arguments.

Ruby:

 def total(*numbers)
 sum = numbers.sum
 puts "Total: #{sum}"
 end

 total(1, 2, 3, 4)

 Calling Methods Inside Methods


Ruby:

 def square(x)
 x * x
 end
 def display_square(num)
 puts "Square is #{square(num)}"
 end
 display_square(5)
 Summary Table
Concept Example Syntax

Define method def name; ...; end

With parameter def greet(name)

With return value return value (or omit for last line)

Default value def greet(name = "Guest")

Multiple args def total(*nums)

Email:
[email protected]

Blogger:
https://souhaillaghchimdev.blogspot.com/

You might also like