Author: Saim Khalid

  • Mixins in Ruby?

    Ruby does not support multiple inheritance. Instead, it uses Mixins (via include keyword).

    module Walkable
      def walk
    
    puts "Walking..."
    end end class Person include Walkable end p = Person.new p.walk #
  • self in Ruby?

    self represents the current object.

    Inside a class → self refers to the object calling the method.

    For class methods → self refers to the class itself.

  • Blocks, Procs, and Lambdas?

    • Block: Anonymous piece of code passed to methods.
    3.times { puts "Hello" }
    
    • Proc: Saved block that can be reused.
    say = Proc.new { puts "Hi" }
    say.call
    
    • Lambda: Like a Proc but stricter about arguments.
    l = ->(x) { x*x }
    puts l.call(5) # 25
    
  • Difference between == and === in Ruby?

    • == → checks equality of values.
    • === → used in case statements and can behave differently depending on the class.
    5 == 5      # true
    (1..10) === 5  # true (range check)
    
  • What are Symbols in Ruby?

    Symbols are immutable, reusable names represented with a colon :.
    They are faster and consume less memory than strings.

    :age   # symbol
    "age"  # string
  • puts, print, and p?

    • puts → prints output with newline.
    • print → prints without newline.
    • p → prints with debugging info (shows object’s raw form).

    Example:

    puts "Hello"   # Hello (new line)
    print "Hello"  # Hello (no new line)
    p "Hello"  
  • 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.

    • Designed by Yukihiro “Matz” Matsumoto in 1995.
    • Popular because of Ruby on Rails framework.
  • 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:


    Ruby is fun!
    Ruby is fun!
    Ruby is fun!
    Hello, Sara
    25