[Interview Series] Ruby high-frequency interview questions

**Welcome to my blog, it’s my pleasure to meet you here! Welcome to subscribe to relevant columns: **

⭐️ The most comprehensive IT Internet company interview guide on the Internet: Collect and organize real interview questions on technology, projects, and HR from all major IT Internet companies on the Internet.
⭐️ Innovation and future in the AIGC era: Explain in detail the concept, core technology, application fields, etc. of AIGC.
⭐️ Full-process data technology practical guide: Comprehensively explain the entire process from data collection to data visualization, and master the core technologies and methods for building modern data platforms and data warehouses.

Article Directory

    • Ruby beginner interview questions with detailed answers
    • 1. What types of variables are there in Ruby?
  • 2. What is a symbol (Symbol) in Ruby?
  • 3. What is a block? How to define and use it?
  • 4. What are Proc and Lambda in Ruby? What's the difference?
  • 5. How to define and call methods in Ruby?
  • 6. What is the difference between classes and modules in Ruby?
  • 7. How to do string interpolation in Ruby?
  • 8. What is an iterator in Ruby? for example.
  • 9. How to implement exception handling in Ruby?
  • 10. How to define and use hashes in Ruby?
  • Ruby intermediate interview questions and detailed answers
    • 1. Explain what Ruby's modules are and how they are used for mixins?
  • 2. How to create and use custom exceptions in Ruby?
  • 3. Explain the difference between Ruby's Block, Proc and Lambda.
  • 4. What is Ruby metaprogramming? Please give an example.
  • 5. How to implement singleton pattern in Ruby?
  • 6. Explain the `super` keyword in Ruby and its usage.
  • 7. What is the `method_missing` method in Ruby? How to use it?
  • 8. How to handle file read and write operations in Ruby?
  • 9. What is the use of `self` keyword in Ruby?
  • 10. Explain the garbage collection mechanism in Ruby.
  • Ruby advanced interview questions and detailed answers
    • 1. Explain the `method_missing` method in Ruby. What is it used for? How to use it?
  • 2. What does the `self` keyword in Ruby mean? What does it mean in different contexts?
  • 3. What are the `include` and `extend` methods in a module? What's the difference?
  • 4. How to implement singleton pattern in Ruby? Provide an example.
  • 5. What is the difference between `Proc` and `Lambda` in Ruby?
  • 6. How does the `super` keyword work in Ruby? Provide an example.
  • 7. What is the difference between `method` and `define_method` in Ruby?
  • 8. Explain the `Enumerable` module in Ruby and its common methods.
  • 9. Explain the garbage collection mechanism in Ruby.
  • 10. How to handle multithreading in Ruby? Briefly describe the method of thread synchronization.
  • Summary of main knowledge points
    • 1. Basic syntax and data types
  • 2. Control flow and iteration
  • 3. Methods and blocks
  • 4. Object-oriented programming
  • 5. Error handling
  • 6. File and I/O operations
  • 7. Metaprogramming
  • 8. Database operations
  • 9. Testing and Debugging
  • 10. Ruby Ecosystem
  • 11. Performance optimization and memory management

Ruby beginner interview questions with detailed answers

1. What types of variables are there in Ruby?

There are four types of variables in Ruby: local variables, global variables, instance variables, and class variables.
answer:

  • Local variables: Start with a lowercase letter or underscore and are only valid within the block, method or class in which it is defined.
  • Global variables: Starting with $, they can be accessed and modified anywhere in the program.
  • Instance variable: Starting with @, it is only valid in a specific object instance.
  • Class variables: Start with @@ and are shared between instances of a class and its subclasses.

2. What is a symbol (Symbol) in Ruby?

Symbols are immutable, unique identifiers, typically used for hash keys or constants.

answer:
Symbols begin with a colon (:), such as :symbol. They are more efficient than strings because they are stored in memory only once, making them suitable for use like hash keys where they need to be reused.

3. What is a block? How to define and use it?

A block is an anonymous function that encapsulates a set of code and can be passed as a parameter to a method.

** Answer: **
Blocks can be surrounded by braces {} or do...end. Usually used with methods like:

[1, 2, 3].each { |num| puts num } 

or

[1, 2, 3].each do |num|
  puts num
end 

4. What are Proc and Lambda in Ruby? What's the difference?

Both Proc and Lambda are objects used to encapsulate code blocks, but they differ in parameter processing and return behavior.

answer:

  • Proc: Created with Proc.new or proc. On return, exit the entire method.
  • Lambda: Created with lambda or ->. On return, exit the lambda itself. There are strict requirements on the number of parameters.
pr = Proc.new { |x, y| puts x + y }
lm = lambda { |x, y| puts x + y } 

5. How to define and call methods in Ruby?

Use the def keyword to define a method, the method name followed by the parameter list, and end to end the definition.

answer:

def greet(name)
  "Hello, #{name}!"
end

puts greet("Alice") 

Output: Hello, Alice!

6. What is the difference between classes and modules in Ruby?

Classes are used to create objects, and modules are used to organize and reuse code, but cannot be instantiated.

answer:

  • Class: Object instances can be created using the class keyword definition.
  • Module: Defined using the module keyword and cannot be instantiated. Used to include methods and constants, and can be mixed into classes with include or extend.
module Greetings
  def hello
    "Hello!"
  end
end

class Person
  include Greetings
end

p = Person.new
puts p.hello  # Output: Hello! 

7. How to do string interpolation in Ruby?

Use the #{} syntax to insert the value of a variable or expression into a string.

answer:

name = "Alice"
puts "Hello, #{name}!"  # Output: Hello, Alice! 

8. What is an iterator in Ruby? for example.

Iterators are methods used to traverse collections (such as arrays, hashes).

answer:
Common iterators such as each, map, select. Example:

[1, 2, 3].each { |num| puts num } 

Output: 1\n2\n3

9. How to implement exception handling in Ruby?

Use the begin...rescue...end structure to handle exceptions.

answer:

begin
  # Code that may throw exceptions
  result = 10 / 0
rescue ZeroDivisionError => e
  puts "Error: #{e.message}"
end 

Output: Error: divided by 0

10. How to define and use hashes in Ruby?

Use curly braces {} to define a hash, and key-value pairs are represented by colons or arrows.

answer:

hash = { key1: 'value1', key2: 'value2' }
puts hash[:key1]  # Output: value1 

These questions cover basic concepts and operations in Ruby programming. Through these questions and detailed answers, you can help beginners perform better in interviews.

Ruby intermediate interview questions and detailed answers

1. Explain what Ruby modules are and how they are used for mixins?

answer:
A module is a collection that can contain methods, classes, constants, and other modules. They cannot be instantiated, but can be included in classes. Through include or extend, modules can mix their methods into classes to achieve code reuse and multiple inheritance.

module Greet
  def greet
    "Hello!"
  end
end

class Person
  include Greet
end

p = Person.new
p.greet # => "Hello!" 

2. How to create and use custom exceptions in Ruby?

answer:
Custom exception classes need to inherit from StandardError or its subclasses. After creating a custom exception, you can raise the exception using the raise keyword and catch the exception using the rescue keyword.

class CustomError < StandardError; end

begin
  raise CustomError, "Something went wrong"
rescue CustomError => e
  puts e.message
end 

3. Explain the difference between Ruby's Block, Proc and Lambda.

answer:
Blocks are anonymous blocks of code that can be passed to methods. Proc is an object that can store blocks of code. Lambda is a special kind of Proc with stricter parameter checking and return behavior.

def example_block
  yield
end

example_block { puts "Block" }

proc = Proc.new { puts "Proc" }
proc.call

lambda = -> { puts "Lambda" }
lambda.call 

4. What is Ruby metaprogramming? Please give an example.

answer:
Metaprogramming is the technique of writing code to manipulate other code. Ruby's metaprogramming allows dynamically creating methods, classes, and modifying existing code. Commonly used metaprogramming techniques include define_method and method_missing.

class MyClass
  define_method(:dynamic_method) do
    "Hello from dynamic method"
  end
end

obj = MyClass.new
puts obj.dynamic_method 

5. How to implement singleton pattern in Ruby?

answer:
You can use the Singleton module to implement the singleton pattern, ensuring that a class has only one instance and providing a global access point.

require 'singleton'

class SingletonClass
  include Singleton
end

obj1 = SingletonClass.instance
obj2 = SingletonClass.instance

puts obj1 == obj2 # => true 

6. Explain the super keyword in Ruby and its usage.

answer:
The super keyword is used to call the method of the same name in the parent class. If there are no parameters, super will pass all parameters of the current method; if there are parameters, super will only pass the specified parameters.

class Parent
  def greet(name)
    "Hello, #{name}"
  end
end

class Child < Parent
  def greet(name)
    super(name) + " from Child"
  end
end

puts Child.new.greet("John") # => "Hello, John from Child" 

7. What is the method_missing method in Ruby? How to use it?

answer:
method_missing is a hook method that is triggered when a method that does not exist on an object is called. You can override the method_missing method in a class to implement dynamic method calling.

class DynamicMethod
  def method_missing(name, *args)
    "You called #{name} with #{args.join(', ')}"
  end
end

obj = DynamicMethod.new
puts obj.undefined_method(1, 2, 3) # => "You called undefined_method with 1, 2, 3" 

8. How to handle file read and write operations in Ruby?

answer:
You can use the File class to handle file reading and writing operations. File.open can open a file and use block operations to ensure that the file is automatically closed after use.

# write file
File.open('example.txt', 'w') do |file|
  file.write("Hello, Ruby!")
end

# read file
File.open('example.txt', 'r') do |file|
  content = file.read
  puts content
end 

9. What is the use of the self keyword in Ruby?

answer:
The self keyword refers to the current object. In class methods, self refers to the class itself; in instance methods, self refers to the instance object. Use self to explicitly call methods of the current object or access properties of the current object.

class MyClass
  def instance_method
    self
  end

  def self.class_method
    self
  end
end

obj = MyClass.new
puts obj.instance_method == obj  # => true
puts MyClass.class_method == MyClass # => true 

10. Explain the garbage collection mechanism in Ruby.

answer:
Ruby uses garbage collection (GC) to automatically manage memory. Ruby's GC is based on the mark-and-sweep algorithm, and incremental and generational garbage collection mechanisms have been introduced in the latest version to improve performance. The GC periodically scans the heap memory, marking objects that are no longer used and freeing their memory.

# Force garbage collection
GC.start 

These questions cover some intermediate concepts in Ruby, and mastering these knowledge points can help interviewees perform well in Ruby interviews.

Ruby advanced interview questions and detailed answers

1. Explain the method_missing method in Ruby. What is it used for? How to use it?

answer:
method_missing is a metaprogramming technique in Ruby. The method_missing method is triggered when a method that does not exist on an object is called. It can be used to catch these calls, perform some default actions or throw custom errors. For example, it is often used in dynamic proxy patterns or when creating flexible APIs.

class DynamicMethodHandler
  def method_missing(method_name, *args, &block)
    puts "You called: #{method_name} with arguments: #{args.join(', ')}"
  end
end

handler = DynamicMethodHandler.new
handler.foo(1, 2, 3)  # Output: You called: foo with arguments: 1, 2, 3 

By defining method_missing, unknown method calls can be handled and the flexibility and extensibility of the class can be enhanced.

2. What does the self keyword in Ruby mean? What does it mean in different contexts?

answer:
self refers to the current object in Ruby. self has different meanings in different contexts:

  • Inside the class definition: self refers to the class itself.
  • Inside an instance method: self refers to the instance to which the method belongs.
  • Inside a class method: self refers to the current class.
    For example:
class MyClass
  def self.class_method
    puts "Class method: #{self}"
  end

  def instance_method
    puts "Instance method: #{self}"
  end
end

MyClass.class_method           # Output: Class method: MyClass
MyClass.new.instance_method    # Output: Instance method: #<MyClass:0x...> 

Understanding self helps to grasp the object context and method calling mechanism.

3. What are the include and extend methods in a module? What's the difference?

answer:

  • include: Mix the module's methods into the class as instance methods so that instances of the class can call these methods.
  • extend: Mix the module's methods into the class as class methods, so that the class itself can call these methods.
module Greetings
  def hello
    "Hello!"
  end
end

class Person
  include Greetings
end

p = Person.new
puts p.hello  # Output: Hello!

class MyClass
  extend Greetings
end

puts MyClass.hello  # Output: Hello! 

include is used for instance method mixing, and extend is used for class method mixing. They provide functional extensions for instances and classes respectively.

4. How to implement singleton pattern in Ruby? Provide an example.

answer:
The singleton pattern can be implemented through the Singleton module, ensuring that a class has only one instance.

require 'singleton'

class SingletonClass
  include Singleton
end

instance1 = SingletonClass.instance
instance2 = SingletonClass.instance

puts instance1.equal?(instance2)  # Output: true 

Through the Singleton module, you can ensure that a class has only one instance, which is suitable for scenarios with globally unique objects.

5. What is the difference between Proc and Lambda in Ruby?

answer:
Proc and Lambda are both closures, but there are some key differences:

  • Return Behavior: Lambda will return from itself, while Proc will return from its containing method.
  • Parameter handling: Lambda checks the number of arguments, Proc does not.
pr = Proc.new { return "Returning from Proc" }
lm = lambda { return "Returning from Lambda" }

def call_proc
  pr.call
  "Returning from method"
end

def call_lambda
  lm.call
  "Returning from method"
end

puts call_proc      # Output: Returning from Proc
puts call_lambda    # Output: Returning from method 

The different features of Proc and Lambda are suitable for different code organization and control flow needs.

6. How does the super keyword work in Ruby? Provide an example.

answer:
super calls a method in the parent class with the same name as the current method. You can pass parameters or not. If no parameters are passed, all parameters of the current method will be passed.

class Parent
  def greet(name)
    "Hello, #{name}!"
  end
end

class Child < Parent
  def greet(name)
    super + " How are you?"
  end
end

child = Child.new
puts child.greet("Alice")  # Output: Hello, Alice! How are you? 

super provides a way to call parent class methods, which facilitates method extension and reuse.

7. What is the difference between method and define_method in Ruby?

answer:

  • method: Get the method object of an object for calling or passing.
  • define_method: Dynamically defined method, used to create methods at runtime.
class MyClass
  define_method(:dynamic_method) do |arg|
    "Hello, #{arg}!"
  end
end

obj = MyClass.new
puts obj.dynamic_method("Ruby")  # Output: Hello, Ruby!

# Using `method`
m = obj.method(:dynamic_method)
puts m.call("World")  # Output: Hello, World! 

method is used to operate existing methods, and define_method is used to dynamically create methods, providing flexible meta-programming capabilities.

8. Explain the Enumerable module in Ruby and its common methods.

answer:
The Enumerable module provides common functions such as collection traversal, search, and sorting. The class needs to implement the each method and contain the Enumerable module.
Commonly used methods:

  • map: Returns a new array containing the block results.
  • select: Returns a new array containing elements that satisfy the block condition.
  • reduce: Apply the block to each element of the collection, accumulating the results.
class MyCollection
  include Enumerable

  def initialize(*items)
    @items = items
  end

  def each
    @items.each { |item| yield item }
  end
end

collection = MyCollection.new(1, 2, 3, 4)
puts collection.map { |x| x * 2 }      # Output: [2, 4, 6, 8]
puts collection.select { |x| x.even? } # Output: [2, 4] 

Enumerable provides powerful collection operation capabilities, improving code simplicity and readability.

9. Explain the garbage collection mechanism in Ruby.

answer:
Ruby uses a mark-and-sweep algorithm for garbage collection. The garbage collector reclaims memory by marking all reachable objects and then clearing unmarked objects. Ruby 2.1 introduced incremental garbage collection, and Ruby 2.2 introduced symbolic garbage collection, improving performance and memory management.

# Example: Creating and discarding objects
1000.times { Object.new }
GC.start  # Manually trigger garbage collection 

Understanding garbage collection can help optimize memory management and performance.

10. How to handle multi-threading in Ruby? Briefly describe the method of thread synchronization.

answer:
Ruby uses the Thread class for multi-threaded programming. Thread synchronization can be achieved through a mutex (Mutex) to avoid race conditions caused by multiple threads accessing shared resources at the same time.

mutex = Mutex.new
counter = 0

threads = 10.times.map do
  Thread.new do
    mutex.synchronize do
      temp = counter
      sleep(0.1)
      counter = temp + 1
    end
  end
end

threads.each(&:join)
puts counter  # Output: 10 

By synchronizing threads with mutexes, shared resources can be safely accessed and modified to avoid concurrency problems.

Summary of main knowledge points

When preparing for a Ruby interview, it is crucial to master the following points. These knowledge points cover content from basic to advanced, and interviewers should have in-depth understanding and practice to demonstrate a comprehensive mastery of the Ruby language and practical application capabilities.

1. Basic syntax and data types

  • Variables and Constants: Understand the use and scope of local variables, global variables, instance variables and class variables. Master the definition and use of constants.
  • Data types: Familiar with Ruby's basic data types such as String, Array, Hash, Symbol, Integer, Float and Boolean, as well as their common methods.
  • Operators: Understand the use of arithmetic operators, comparison operators, logical operators and bitwise operators.

2. Control flow and iteration

  • Conditional statements: Master the use of if, else, elsif, unless, case and the ternary operator.
  • Loop statements: Familiar with while, until, for loops, and iterators such as each, map, select, reject, reduce, etc.

3. Methods and blocks

  • Method definition and invocation: Understand method definition, parameter transfer (including default parameters and variable parameters), return value and method invocation.
  • Block, Proc and Lambda: Understand the concept and usage scenarios of block (Block), understand the difference and usage of Proc and Lambda, as well as their creation and calling.

4. Object-oriented programming

  • Classes and Objects: Master the definition of classes, creation of objects, use of instance variables and class variables, and the initialize method.
  • Inheritance and modules: Understand the inheritance mechanism of classes, master the super keyword, understand the role of modules and the use of include and extend.
  • Polymorphism and Interfaces: Understand how Ruby implements polymorphism and implements interfaces through duck typing.

5. Error handling

  • Exception handling: Master the catching and handling of exceptions, use the begin, rescue, ensure and raise keywords to handle exceptions, and understand the creation and use of custom exception classes.

6. File and I/O operations

  • File Operation: Understand the reading and writing of files, use the File class and the IO class to perform file operations, and master the file modes (such as reading, writing, appending).
  • Standard input and output: Be familiar with puts, print, gets and other methods for standard input and output operations.

7. Metaprogramming

  • Dynamic methods: Understand the usage of method_missing and define_method, and master how to dynamically define and call methods.
  • Reflection: Understand the use of send method and respond_to? method, and operate objects through the reflection mechanism.

8. Database operations

  • ActiveRecord: Master the ActiveRecord model in Ruby on Rails, understand the basic concepts of ORM, and be familiar with common database operations such as query, insert, update, and delete.
  • Database Connection: Learn how to use Ruby to connect and operate different types of databases (such as SQLite, PostgreSQL, MySQL).

9. Testing and Debugging

  • Testing framework: Master the basic use of commonly used testing frameworks such as RSpec and Minitest, and understand the differences and usage of unit testing, functional testing and integration testing.
  • Debugging skills: Be familiar with debugging tools such as byebug and pry, and master how to set breakpoints, check variables and stack information.

10. Ruby Ecosystem

  • Gem and Bundler: Understand the role of RubyGems and master how to use gem and Bundler to manage dependencies.
  • Ruby on Rails: Understand the basic architecture and common components of the Ruby on Rails framework, and master the creation, configuration and deployment of Rails applications.

11. Performance optimization and memory management

  • Performance Tuning: Understand common performance problems, master performance analysis tools such as benchmark and memory_profiler, and learn how to optimize code performance.
  • Garbage Collection: Understand Ruby's garbage collection mechanism and understand how to tune garbage collection to improve application performance.

By in-depth understanding and practice of these knowledge points, interviewers can demonstrate a comprehensive mastery of the Ruby language and perform well in the interview. Proficiency in these areas will help you tackle a variety of complex interview questions and real-world programming challenges.