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.
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.
3.times { puts “Ruby is fun!” }
say_hello = Proc.new { |name| puts “Hello, #{name}” }
say_hello.call(“Sara”)
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:
Ruby is fun!
Ruby is fun!
Ruby is fun!
Hello, Sara
25
class Person
attr_accessor :name, :age # creates getter & setter
def initialize(name, age) # constructor
@name = name
@age = age
end
def introduce
“Hi, I’m #{@name} and I’m #{@age} years old.”
end
end
p1 = Person.new(“Ali”, 25)
puts p1.introduce
class 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.
def greet(name)
return “Hello, #{name}!”
end
puts greet(“Ayesha”)
def starts a method, end closes it.
return gives back a value.
Output:
Hello, Ayesha!
i = 1
while i <= 5
puts i
i += 1
end
1
2
3
4
5
for n in 1..5
puts n
end
1..5
means range from 1 to 5.1 2 3 4 5
[1, 2, 3, 4, 5].each do |num|
puts num * 2
end
2
4
6
8
10
age = 18
if age >= 18
puts “You are an adult.”
elsif age >= 13
puts “You are a teenager.”
else
puts “You are a child.”
end
if … elsif … else … end is used for decision making.
Output:
You are an adult.
student = { “name” => “Ali”, “age” => 22, “grade” => “A” }
puts student[“name”] # Ali
student[“age”] = 23 # update
puts student.inspect
Hashes store key-value pairs.
Keys can be strings “name” or symbols :name.
Output:
Ali
{“name”=>”Ali”, “age”=>23, “grade”=>”A”}
fruits = [“apple”, “banana”, “cherry”]
puts fruits[0] # apple
puts fruits.length # 3
fruits << “mango” # Add new element
puts fruits.inspect # Show complete array
Arrays store multiple values.
Index starts from 0.
<< means “append”.
Output:
apple
3
[“apple”, “banana”, “cherry”, “mango”]
name = “Saim” # String
age = 25 # Integer
height = 5.9 # Float
is_student = true # Boolean
puts “Name: #{name}, Age: #{age}, Height: #{height}, Student: #{is_student}”
Ruby is dynamically typed → no need to mention string, int, etc.
Output:
Name: Saim, Age: 25, Height: 5.9, Student: true
puts “Hello, World!”
puts → Prints text with a new line at the end.
“Hello, World!” is a string.
Output:
Hello, World!