Category: Examples
-
File Handling
ontent“w” → write mode (creates file if not exist). File.read → reads entire file content. Output in console: Hello Ruby File!And file test.txt is created with that text.
-
Blocks, Procs, Lambdas
Block 3.times { puts “Ruby is fun!” } Proc say_hello = Proc.new { |name| puts “Hello, #{name}” }say_hello.call(“Sara”) Lambda square = -> (x) { x * x }puts square.call(5)Block → Small piece of code in {} or do…end. Proc → Stored block that can be reused. Lambda → Like Proc but stricter with arguments. Output:…
-
Classes and Objects
class Personattr_accessor :name, :age # creates getter & setter def initialize(name, age) # constructor@name = name@age = ageend def introduce“Hi, I’m #{@name} and I’m #{@age} years old.”endend p1 = Person.new(“Ali”, 25)puts p1.introduceclass defines a blueprint. @name and @age are instance variables. initialize runs when object is created.Output: Hi, I’m Ali and I’m 25 years old.
-
Conditions
age = 18 if age >= 18puts “You are an adult.”elsif age >= 13puts “You are a teenager.”elseputs “You are a child.”endif … elsif … else … end is used for decision making.Output: You are an adult.
-
Hashes (Dictionary / Map)
student = { “name” => “Ali”, “age” => 22, “grade” => “A” }puts student[“name”] # Alistudent[“age”] = 23 # updateputs student.inspectHashes store key-value pairs. Keys can be strings “name” or symbols :name.Output: Ali{“name”=>”Ali”, “age”=>23, “grade”=>”A”}
-
Arrays
fruits = [“apple”, “banana”, “cherry”] puts fruits[0] # appleputs fruits.length # 3fruits << “mango” # Add new elementputs fruits.inspect # Show complete arrayArrays store multiple values. Index starts from 0. << means “append”. Output: apple3[“apple”, “banana”, “cherry”, “mango”]
-
Variables and Data Types
name = “Saim” # Stringage = 25 # Integerheight = 5.9 # Floatis_student = true # Boolean puts “Name: #{name}, Age: #{age}, Height: #{height}, Student: #{is_student}”Ruby is dynamically typed → no need to mention string, int, etc. {} → used inside strings for interpolation (inserting values). Output: Name: Saim, Age: 25, Height: 5.9, Student: true
-
Hello World
puts “Hello, World!”puts → Prints text with a new line at the end. “Hello, World!” is a string.Output: Hello, World!