Category: Interview Questions

  • Garbage Collection in Ruby?

    • Ruby has automatic garbage collection.
    • It removes objects from memory that are no longer referenced.
    • This prevents memory leaks.
  • Explain method missing?

    If you call a method that doesn’t exist, Ruby calls method_missing.
    You can override it to handle undefined methods.

    class MyClass
      def method_missing(name, *args)
    
    puts "Method #{name} is missing!"
    end end obj = MyClass.new obj.hello #

  • Explain super keyword?

    • Calls the method of the same name from parent class.
    class Animal
      def speak
    
    "Animal sound"
    end end class Dog < Animal def speak
    super + " Woof!"
    end end puts Dog.new.speak # Output: "Animal sound Woof!"

  • Duck Typing in Ruby?

    In Ruby, type is determined by behavior (methods), not class.
    If an object can perform required actions, it can be used.

    def make_it_talk(obj)
      obj.talk
    end
    
    class Dog
      def talk; puts "Woof!"; end
    end
    
    class Human
      def talk; puts "Hello!"; end
    end
    
    make_it_talk(Dog.new)   # Woof!
    make_it_talk(Human.new) # Hello!
    
  • 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"