Ruby / Basic

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!"
Ruby

2. 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."
Ruby

3. 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
Ruby

4. 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
Ruby

5. 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
Ruby

6. Methods (Functions)

Methods are reusable blocks of code that perform specific tasks.

๐Ÿ‘‰ Example:

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

greet("Alice")
greet("Bob")
Ruby

7. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *