Author: Saim Khalid

  • What are Ruby’s key features?

    Pure OOP → Everything is an object. Dynamic Typing → No need to declare variable types. Duck Typing → If it “quacks like a duck”, it can be treated as one. Garbage Collection → Memory management is automatic. Mixins (Modules) → Instead of multiple inheritance, Ruby uses modules.

  • What is Ruby?

    Ruby is a high-level, interpreted, object-oriented scripting language designed for simplicity and productivity. It has elegant syntax that is natural to read and easy to write.

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

  • Methods

    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!

  • Loops

    While Loop For Loop Each Loop

  • 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”]