Learning Ruby starts with understanding its simple and elegant syntax. Below are the fundamental topics for beginners, each explained with examples you can try yourself.
1. Introduction to Ruby
Ruby is a high-level, interpreted programming language that focuses on productivity and simplicity. It is widely used in web development (Ruby on Rails), scripting, and automation.
๐ Hello World Example:
puts "Hello, World!"
Ruby2. Variables and Data Types
Variables are used to store data. Ruby supports different data types like strings, integers, floats, booleans, and symbols.
๐ Example:
name = "Alice" # String
age = 25 # Integer
height = 1.68 # Float
is_student = true # Boolean
role = :admin # Symbol
puts "#{name} is #{age} years old."
Ruby3. Operators
Ruby supports arithmetic, comparison, and logical operators.
๐ Example:
x = 10
y = 5
# Arithmetic
puts x + y # 15
puts x - y # 5
puts x * y # 50
puts x / y # 2
# Comparison
puts x > y # true
puts x == y # false
# Logical
puts (x > 5 && y < 10) # true
puts (x < 5 || y == 5) # true
Ruby4. Control Structures (if, else, elsif, unless, case)
Control structures help decision-making in Ruby programs.
๐ Example with if/else:
temperature = 20
if temperature > 25
puts "It's hot outside."
elsif temperature >= 15
puts "The weather is nice."
else
puts "It's cold outside."
end
Ruby๐ Example with case:
grade = "B"
case grade
when "A"
puts "Excellent!"
when "B"
puts "Good job!"
when "C"
puts "You passed."
else
puts "Try again!"
end
Ruby5. Loops (while, until, for, .each)
Loops repeat code until a condition is met.
๐ While Loop:
i = 1
while i <= 5
puts "Count: #{i}"
i += 1
end
Ruby๐ Each Loop with Array:
fruits = ["apple", "banana", "cherry"]
fruits.each do |fruit|
puts "I like #{fruit}"
end
Ruby6. Methods (Functions)
Methods are reusable blocks of code that perform specific tasks.
๐ Example:
def greet(name)
puts "Hello, #{name}!"
end
greet("Alice")
greet("Bob")
Ruby7. Basic Input & Output
Ruby can take input from the user and display output.
๐ Example:
puts "Enter your name:"
name = gets.chomp # gets input, chomp removes newline
puts "Welcome, #{name}!"
Rubyโ With these basics, you can start writing simple Ruby scripts. Once comfortable, youโll be ready to explore intermediate topics like arrays, hashes, and object-oriented programming.
