{"id":22814295,"url":"https://github.com/devinterview-io/ruby-interview-questions","last_synced_at":"2025-06-17T08:05:01.273Z","repository":{"id":108758164,"uuid":"332193376","full_name":"Devinterview-io/ruby-interview-questions","owner":"Devinterview-io","description":"🟣 Ruby interview questions and answers to help you prepare for your next technical interview in 2025.","archived":false,"fork":false,"pushed_at":"2025-05-19T16:58:26.000Z","size":40,"stargazers_count":8,"open_issues_count":0,"forks_count":4,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-05-19T18:01:26.835Z","etag":null,"topics":["coding-interview-questions","coding-interviews","interview-practice","interview-prep","interview-preparation","leetcode-questions","leetcode-solutions","programming-interview-questions","ruby","ruby-interview-questions","ruby-questions","ruby-tech-interview","software-developer-interview","software-engineer-interview","software-engineering","technical-interview-questions","web-and-mobile-development-interview-questions"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Devinterview-io.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2021-01-23T11:25:44.000Z","updated_at":"2025-05-19T16:58:29.000Z","dependencies_parsed_at":"2025-04-15T10:31:28.820Z","dependency_job_id":null,"html_url":"https://github.com/Devinterview-io/ruby-interview-questions","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Devinterview-io/ruby-interview-questions","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Fruby-interview-questions","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Fruby-interview-questions/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Fruby-interview-questions/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Fruby-interview-questions/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Devinterview-io","download_url":"https://codeload.github.com/Devinterview-io/ruby-interview-questions/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Fruby-interview-questions/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":260318655,"owners_count":22991117,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["coding-interview-questions","coding-interviews","interview-practice","interview-prep","interview-preparation","leetcode-questions","leetcode-solutions","programming-interview-questions","ruby","ruby-interview-questions","ruby-questions","ruby-tech-interview","software-developer-interview","software-engineer-interview","software-engineering","technical-interview-questions","web-and-mobile-development-interview-questions"],"created_at":"2024-12-12T13:08:00.929Z","updated_at":"2025-06-17T08:05:01.261Z","avatar_url":"https://github.com/Devinterview-io.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# 100 Core Ruby Interview Questions in 2025\n\n\u003cdiv\u003e\n\u003cp align=\"center\"\u003e\n\u003ca href=\"https://devinterview.io/questions/web-and-mobile-development/\"\u003e\n\u003cimg src=\"https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/github-blog-img%2Fweb-and-mobile-development-github-img.jpg?alt=media\u0026token=1b5eeecc-c9fb-49f5-9e03-50cf2e309555\" alt=\"web-and-mobile-development\" width=\"100%\"\u003e\n\u003c/a\u003e\n\u003c/p\u003e\n\n#### You can also find all 100 answers here 👉 [Devinterview.io - Ruby](https://devinterview.io/questions/web-and-mobile-development/ruby-interview-questions)\n\n\u003cbr\u003e\n\n## 1. What is _Ruby_, and why is it popular for web development?\n\n**Ruby** is a dynamic, object-oriented programming language known for its simplicity and focus on developer productivity. Its main claim to fame in web development is the **web application framework**, **Ruby on Rails** (RoR), which transformed the way web applications are built by promoting convention over configuration.\n\n### Key Features \u0026 Contributions to Web Development\n\n- **Language Syntax**: Ruby's syntax has an appeasing natural language style. This, paired with its dynamic typing, powerful metaprogramming features, and absence of semicolons, results in clean and expressive code.\n\n- **Gems**: Ruby's package manager, **RubyGems**, simplifies library management, making it easy to integrate numerous third-party extensions.\n\n- **Database Integration**: ActiveRecord, a popular object-relational mapping system, aids in managing database records via a natural, object-oriented interface.\n\n- **MVC Pattern**: Rails, in particular, is famed for its adherence to the Model-View-Controller pattern, offering a clear separation of concerns.\n\n- **Code Rearrangement**: The **auto-loading mechanism** allows for seamless navigation between related files and classes while coding.\n\n- **Ecosystem Consistency**: RoR brought about a `many`-`to`-`many` relationship with databases, streamlining and simplifying existing **development patterns**.\n\n- **Strong Community**: The language's supportive community and its commitment to clean, readable code are evident in guiding principles like \"Mediterranean\" quality and \"Matz's kindness.\"\n\n- **Test-Driven Development**: RoR promotes best-testing practices from the project's inception, ensuring reliability.\n\n- **Giant Corporations' Indulgence**: Prominent organizations such as GitHub, Shopify, and Airbnb have successfully tapped into the potential of Ruby on Rails.\n\n### Code Example: Ruby on Rails (RoR) Routing\n\nHere is the Ruby code:\n\n```ruby\n# config/routes.rb\nRails.application.routes.draw do\n  root 'welcome#index'\n  get 'products/:id', to: 'products#show'\n  resources :articles\nend\n```\n\nThis file configures routes for different URLs, specifying which controllers and actions to invoke. For instance, upon receiving a `GET` request for `products/5`, RoR would route it to the `show` action in the `ProductsController` with the ID parameter set to `5`. Such straightforward setups contribute to RoR's appeal.\n\u003cbr\u003e\n\n## 2. How do you create a _Ruby script file_ and execute it on a _command line_?\n\nFirst, you create a `Ruby` script file with a `.rb` extension that contains your Ruby code. You can then **execute** this script using the `ruby` command in your command line.\n\n### Basic Steps for Creating and Running a Ruby Script in a File\n\n1.  **Create a File**: Use any text editor to write your Ruby code, and save the file with a `.rb` extension, e.g., `my_ruby_script.rb`.\n\n2. **Write Ruby Code**: Here is a simple example.\n\n    ```ruby\n    # Filename: my_ruby_script.rb\n    puts \"Hello, Ruby Script!\"\n    ```\n\n3. **Run the Ruby Script**: Go to your command line and navigate to the folder where the Ruby file is saved. Then, type the following command:\n\n   ```bash\n   ruby my_ruby_script.rb\n   ```\n\n   After pressing enter, you will see the output:\n   \n   ```bash\n   Hello, Ruby Script!\n   ```\n\n### Getting More Advanced\n\n#### Command-Line Arguments\n\nYou can access **command-line arguments** using special variables called `ARGV`.\n\nHere is the code:\n\n```ruby\n# Filename: script_with_args.rb\nputs \"Arguments: #{ARGV.join(', ')}\"\n```\n\nIn the command line, you would run this script as:\n\n```bash\nruby script_with_args.rb arg1 arg2 arg3\n```\n\nThe output would be:\n\n```bash\nArguments: arg1, arg2, arg3\n```\n\n#### Interactive Scripts\n\nRuby scripts can engage with users using the `gets` method.\n\nHere is an example:\n\n```ruby\n# Filename: interactive_script.rb\nputs \"What is your name?\"\nname = gets.chomp\nputs \"Hello, #{name}!\"\n```\n\nWhen you run this script using `ruby interactive_script.rb`, it will prompt you for your name, and after you provide it, it will greet you.\n\n#### Background Processing\n\nIf you want a script to run in the background without blocking your command line, you can use the `\u0026` character.\n\nFor instance, to run a script called `background_script.rb` in the background, you can use:\n\n```bash\nruby background_script.rb \u0026\n```\n\n#### Ruby Shell\n\nFor more complex shell operations, `Ruby` offers the `shell` library.\n\nHere is the sample code:\n\n```ruby\nrequire 'shell'\n\n# Use 'open' to open a URL in your default browser.\nsh = Shell.new\nsh.open \"https://example.com\"\n```\n\u003cbr\u003e\n\n## 3. What are the basic _data types_ in _Ruby_?\n\n**Ruby** is claimed to treat \"everything as an object\". But like many languages, Ruby has both **primitive** and **abstract data types**.\n\n### Primitive Types\n\n- **Numbers**:\n  - **Integers** can be of any size (limited by system memory).\n  - **Floating-Point** numbers follow the IEEE 754 standard.\n- **Booleans**: Represented by `true` and `false`.\n- **Symbols**: Unique, immutable identifiers represented with a `:` followed by a name.\n\n### Abstract Types\n\n- **Strings**: Unicode with multiple encodings.\n- **Arrays**: Ordered, indexed collections.\n- **Hashes**: Key-value pairs, also known as dictionaries or maps in other languages.\n\n### Others assimilated Primitive Types\n\nRuby, despite its philosophy of being completely object-oriented, has some underlying **primitive paradigms** due to its performance concerns and efficiency considerations.\n\n- **nil**: Represents 'nothing' or 'empty'. It's the only instance of `NilClass`.\n\n- **Booleans**: While `true` and `false` are themselves keywords, any other value in Ruby is considered truthy in a conditional context.\n\n### Advanced Types\n\n- **Rational Numbers**: Represented as a fraction (e.g., `1/3r`).\n- **Complex Numbers**: Have real and imaginary parts (e.g., `2 + 3i`).\n- **Dates and Times**: Provide various built-in classes like `Time` for dealing with date and time values.\n\n### Ruby Uniqueness\n\nRuby shuns a \"strictly-typed\" system. **Variables need not be declared upfront** and can be reassigned to different types during execution. This freedom, although liberating, can lead to unexpected behavior, especially in larger codebases.\n\u003cbr\u003e\n\n## 4. Explain the difference between _symbols_ and _strings_ in _Ruby_.\n\n**Ruby** features both strings and **symbols**, each with distinct use cases.\n\n### Key Distinctions\n\n- **Type**: Strings are of class `String`, while symbols are instances of `Symbol`.\n- **Mutability**: Strings are mutable, symbols are not.\n- **Memory**: Symbols are stored as a single, unique object in memory, while each string is unique.\n- **Performance**: As symbols are immutable, **lookups** are faster than for equivalent strings.\n\n### Primary Usages\n\n- **Strings**: For text and dynamic data that may change or be unique across different objects or occurrences.\n- **Symbols**: Typically used as keys for hashes or unique identifiers in the program. They're advantageous for **lookup efficiency** and when the actual content of the identifier is less relevant than its unique identity.\n\n### Memory Considerations\n\n- As symbols are **stored only once** in memory, they are memory-efficient in certain scenarios, like using the same symbol across different objects or operations. Be cautious, though, as unnecessarily creating a large number of symbols can lead to memory bloat.\n- Strings may be more memory-intensive, especially when there are numerous unique strings. However, they are the right choice when dealing with data that genuinely varies or where mutability is required.\n\n### Code Example: String vs Symbol\n\nHere is the Ruby code:\n\n```ruby\n# Strings\nstr_1 = \"Hello\"\nstr_2 = \"Hello\"\nputs str_1.object_id == str_2.object_id  # Output: false\n\n# Symbols\nsym_1 = :hello\nsym_2 = :hello\nputs sym_1.object_id == sym_2.object_id  # Output: true\n```\n\u003cbr\u003e\n\n## 5. How are _constants_ declared and what is their _scope_ in _Ruby_?\n\nIn Ruby, you declare a constant by using all uppercase letters. Constants are subject to lexical scoping. While **reassignment** is technically possible (spawning a warning), it should be avoided as a practice.\n\n### Constant Declaration\n\nYou can declare a Ruby constant using `Object::CONSTANT` notation or by assigning a **value directly to an identifier**.\n\n#### Code Example: Constant Declaration \n\n```ruby\n# Using Object::CONSTANT notation\nMath::PI \n\n# Direct assignment\nRADIUS = 5.0\n```\n\n### Constant Scope\n\nConstants have a **global scope**, but their visibility can be restricted within classes and modules.\n\n#### Global VS. Local Scope\n\n- **Global Scope**: Constants are accessible throughout the entire application.\n  ```ruby\n  A = 1     # Top level\n  module M\n    puts A  # Outputs: 1\n  end\n  ```\n\n- **Local Scope**: Constants are defined within a module or a class.\n  ```ruby\n  module M\n    A = 2\n    A = 3\n    puts A  # Outputs: 3\n  end\n  ```\n\n### Best Practices\n\n- **Avoid** re-assigning constants. Although this generates a warning, the reassignment can still take place, which can lead to unintended behavior.\n- For areas where you want to have a **constant's value remain unchanged**, use `.freeze` on the constant or variable storing the constant's value.\n  \n#### Code Example: Avoiding Reassignment\n\n```ruby\nrequire \"warning\"\n\n# Generates a warning: already initialized constant\nA = 1\nA = 2 \n\nwarning 'constant reassignment'\n\nputs A  # Outputs: 2\n```\n\n#### `Object#freeze`\n\n```ruby\nCIRCLE_AREA = Math::PI * (RADIUS ** 2)\nCIRCLE_AREA.freeze\n\n# Any reassignment will generate an error\n# CIRCLE_AREA = 100 \n\nputs CIRCLE_AREA\n```\n\u003cbr\u003e\n\n## 6. Explain the use of '_require_' and '_include_' in _Ruby_.\n\n**Ruby** uses both **Require** and **Include** to manage dependencies and to mix modules into classes.\n\n### Require\n\n- **Purpose**: Loads external libraries, enabling access to their defined classes and modules.\n\n- **Execution**: Done at the top of the file or script.\n\n- **Trigger**: A `LoadError` is raised if the required file is not found.\n\n- **State Management**: Tracks loaded libraries, subsequently ignoring further `require` calls for the same library.\n\n### Example: Using Require\n\nHere is the Ruby code:\n\n```ruby\n# In file application.rb\nrequire 'my_library'\n\n# In file my_library.rb\nclass MyLibrary\n  # ...\nend\n```\n\n### Include\n\n- **Purpose**: Integrates a module's methods within a class, giving the class access to those methods.\n\n- **Execution**: On the specific class that necessitates the module's functionality.\n\n- **State**: Not applicable for classes, as they can include multiple modules.\n\n#### Why is it Used?\n\n- **Require**: Ensures the presence of the external library before continuing, a basic necessity for external code.\n- **Include**: Mixes in module functionality only when needed, aligning with Rails' convention of using it in the classes contextually.\n\u003cbr\u003e\n\n## 7. What are _Ruby iterators_ and how do they work?\n\nWhen it comes to Ruby, iterators **allow for easy, streamlined data manipulation**. Whether you're working with arrays, ranges, or other data structures, iterators help you efficiently apply operations to each element without needing to manage loop counters.\n\n### Most Common Ruby Iterators\n\n- **Each**: The most basic iterator, it goes through each element.\n- **Each with index**: Similar to each, but it also gives the index of the current element.\n\n### Code Example: Each \u0026 Each with Index\n\nHere is the Ruby code:\n\n```ruby\narr = [5, 4, 3, 2, 1]\n\n# Iterating with Each\narr.each { |num| puts num }\n\n# Output:\n# 5\n# 4\n# 3\n# 2\n# 1\n\n# Iterating with Each with Index\narr.each_with_index { |num, index| puts \"#{index}: #{num}\" }\n\n# Output:\n# 0: 5\n# 1: 4\n# 2: 3\n# 3: 2\n# 4: 1\n```\n\n### Common Usage\n\n- **Each Char**: Often used with strings, this iterator loops through each character.\n- **Each Line**: Handy for reading files, it processes lines one at a time.\n\n### Code Example: Each Char \u0026 Each Line\n\nHere is the Ruby code:\n\n```ruby\nstr = \"Hello, World!\"\n\n# Iterating Each Character\nstr.each_char { |char| puts char }\n\n# Output:\n# H\n# e\n# l\n# l\n# o\n# ,\n# ...\n```\n\n```ruby\nFile.open('example.txt').each_line do |line|\n  puts line\nend\n```\n\n### Predicative Iterators\n\nThese iterators select elements from a collection that match specific conditions. They are typically used in combination with **blocks**.\n\nExamples include `select`, `reject`, and `grep`. Each is designed to achieve specific selection goals:\n\n- `select` returns elements that yield true in the block.\n- `reject` returns elements that yield false in the block.\n- `grep` returns elements that match a specified pattern.\n\n### Code Example: `select`, `reject`, and `grep`\n\nHere is the Ruby code:\n\n```ruby\n# Select even numbers\nnumbers.select { |num| num.even? }\n\n# Reject short names\nnames.reject { |name| name.length \u003c 5 }\n\n# Grep to find email addresses\ntext = \"Email me at user@example.com\"\ntext.grep(/\\b\\w+@\\w+\\.\\w+\\b/)\n```\n\n### Chase \u0026 Transform\n\nThese iterators process the elements and return a result. They include `map`, `collect`, and `partition`.\n\n- `map`: Transforms each input and returns a new array.\n- `collect`: Identical to map, but ops include the return value.\n- `partition`: Separates elements into two groups based on whether the block returns true or false.\n\n### Code Example: `map`, `collect`, and `partition`\n\nHere is the Ruby code:\n\n```ruby\n# Double each number\nnumbers.map { |num| num * 2 }\n\n# Names all uppercase\nnames.collect { |name| name.upcase }\n\n# Split numbers based on even or odd\nnumbers.partition { |num| num.even? }\n```\n\n### Execute Operations\n\nThese iterators modify their elements or perform side effects. Examples include `each` and `each_with_index`.\n\nOften used for their simplicity, do exercise caution as these functions can have unexpected results, especially when combined with unintended side effects.\n\n- `each`: Processes each element but does not return anything.\n- `each_with_index`: Similar to each, but also gives the index of the current element.\n\n### Sort-Related Operations\n\nWhen working with ordered collections like arrays or ranges, Ruby provides various sorting options. Common sorting iterators include `sort`, `sort_by`, and `reverse_each`. They all work with blocks to customize the sorting or iteration behavior.\n\n### Repetition-Based Iterators\n\nThese Ruby constructs are particularly useful in the context of text manipulation, allowing you to repeat characters (such as hyphens for formatting headers) for a specified number of times.\n\n- `each_line`: Useful when processing multi-line strings or files.\n- `each_char`: Ideal for character-level processing in strings or enumerations.\n- `downto`: Iterates downwards to a specified value.\n- `upto`: Iterates upwards to a specified value.\n- `times`: Repeats the associated block a predetermined number of times.\n- `step`: Indents a set number of times, confined by a range.\n- `cycle`: Used primarily with blocks, it repeatedly moves through the specified range.\n\n### Code Example: Repetition-Based Iterators\n\nHere is the Ruby code:\n\n```ruby\n# Print a line of stars\n'*'.upto('*****') { |s| puts s }\n\n# Output:\n# *\n# **\n# ***\n# ****\n# *****\n\n# Print numbers from 5 to 10, then their squares\n5.upto(10) { |num| puts num }\n5.upto(10).each { |num| puts num**2 }\n```\n\u003cbr\u003e\n\n## 8. How are _errors_ handled in _Ruby_?\n\nRuby's **exception hierarchy** enables developers to manage different kinds of errors. The two main exception types cater to a multitude of issues:\n\n- **StandardError**: For generic problems that occur during code execution.\n- **SystemCallError**: Specifically deals with errors originating from system calls.\n\n### Ways to _Handle Exceptions_ in Ruby\n\n#### Top-Level Exception Handling\n\nRuby leverages the `at_exit` method for centralized error handling. This approach is mainly useful for logging errors before program exit or for cleaning up resources.\n\n```ruby\nat_exit do\n  puts $!.message if $!\nend\n```\n\n#### Single Statement Unwind\n\nUtilize **inline rescue**, marked by the `begin` and `end` block. If an exception arises during the evaluation of the enclosed expression, it's caught.\n\n```ruby\nresult = begin\n  raise StandardError, \"This is an error\"\nrescue StandardError =\u003e e\n  \"Rescued: #{e.message}\"\nend\n\nputs result  # Output: Rescued: This is an error\n```\n\n### Custom Exception Handling\n\nDevelopers benefit from creating their custom exception classes or identifying specific exception types to tailor their error management strategies.\n\n#### Defining Custom Exception Classes\n\nThe `Exception` class or, more preferably, its subclass, `StandardError`, are parents to all user-defined exceptions. This inheritance ensures that all custom exceptions are catchable via `rescue`.\n\n```ruby\nclass MyCustomError \u003c StandardError\n  # Additional behavior or settings\nend\n\nraise MyCustomError, \"Something went wrong!\"\n```\n\n#### Identifying the Right Exception\n\nAn error's distinct nature often demands a corresponding exception. For instance, consider a method handling file operations:\n\n```ruby\ndef read_file(file_path)\n  raise ArgumentError, \"File path is empty\" if file_path.to_s.empty?\n  raise IOError, \"File not found\" unless File.exist?(file_path)\n\n  File.read(file_path)\nend\n```\n\nUpon calling `read_file`, any exception correlated to an invalid file path can be reliably caught and addressed with a targeted `rescue` block.\n\n### Error Handling Best Practices\n\n- **Keep it Precise**: Make use of granular `rescue` blocks or `case` statements to align the corrective measures with the specific error.\n  \n- **Maintain a Balance**: Overuse of exceptions can convolute code and hinder its readability. Carefully select the exceptions likely to surface and necessitate special attention.\n\n- **Locale Transparency**: Choose either a local exception resolver that terminates in the current method or a global one that percolates up the call stack, but aim for consistency.\n\n### Performance Considerations\n\nWhile exceptions can be invaluable for isolated and unexpected mishaps, triggering and managing them incurs a performance cost. It's typically wiser to leverage them predominantly in such scenarios and not as part of conventional program flow.\n\u003cbr\u003e\n\n## 9. Describe the difference between _local_, _instance_, and _class variables_.\n\nLet's set the record straight on the differences between **local**, **instance**, and **class variables** in Ruby.\n\n### Common Features\n\nAll three variable types support:\n\n- **naming**: ![A-Za-z0-9_](2, 50)\n- **assignment**: `variable_name = value`\n- **access control**: `public`, `private`, and `protected`\n- **immediacy**: their scope begins from where they are initialized and exists until the scope ends.\n\n### Local Variables\n\n- **Scope**: Limited to the block where they are defined.\n- **Life Cycle**: Created when the program reaches their definition and destroyed when the block is exited.\n\n#### Example: Local Variable\n\nHere is the Ruby code:\n\n```ruby\ndef hello\n  name = \"Ruby\"\n  puts \"Hello, #{name}!\"  # Output: Hello, Ruby!\nend\n\n# Accessing name outside its defined block will cause an error.\n# puts name  # Will raise an error\n```\n\n### Instance Variables\n\n#### Naming Convention\n\nAn instance variable is **prefixed with a single '@' symbol**.\n\n- **Scope**: Primarily within the class, but is accessible from outside the class if the class is instantiated.\n- **Life Cycle**: Created when an object is instantiated and remains available until that particular object is destroyed.\n\n#### Example: Instance Variable\n\nHere is the Ruby code:\n\n```ruby\nclass Greeting\n  def set_name(name)\n    @name = name\n  end\n\n  def display_greeting\n    puts \"Hello, #{@name}!\"  # Output: Hello, Ruby!\n  end\nend\n\ngreeting_instance = Greeting.new\ngreeting_instance.set_name(\"Ruby\")\ngreeting_instance.display_greeting\n```\n\n### Class Variables\n\n#### Naming Convention\n\nA class variable is **prefixed with two '@' symbols**.\n\n- **Scope**: Within the class and its inheritors but not accessible from outside.\n- **Life Cycle**: Created when assigned within the class or its inheritors and accessible as long as the class or one of its inheritors is in memory.\n\n#### Example: Class Variable\n\nHere is the Ruby code:\n\n```ruby\nclass Employee\n  @@company_name = \"ABC Corporation\"\n\n  def self.company_name=(name)\n    @@company_name = name\n  end\n\n  def display_company_name\n    puts @@company_name\n  end\nend\n\nemployee1 = Employee.new\nemployee2 = Employee.new\n\n# Output: \"ABC Corporation\" for both employee1 and employee2.\nemployee1.display_company_name\nemployee2.display_company_name\n\nEmployee.company_name = \"New Company\"  # changes the class variable\n\n# After changing, outputs for both employee1 and employee2 will be \"New Company\".\nemployee1.display_company_name\nemployee2.display_company_name\n```\n\u003cbr\u003e\n\n## 10. What are _Ruby's accessor methods_?\n\nIn Ruby, **accessor methods** allow you to manipulate object attributes. There are three types of accessor methods: **`attr_reader`**, **`attr_writer`**, and **`attr_accessor`**, each serving a specific role in the attribute's lifecycle\n\n### Attribute Methods\n\n- **`attr_reader`**: Generates a simple getter method for an attribute. It can be accessed but not modified externally.\n- **`attr_writer`**: Generates a basic setter method. The attribute can be modified but not read externally.\n- **`attr_accessor`**: Combines both getter and writer methods in one. This creates a full-fledged getter and setter for the attribute.\n\n### Code Example: Accessor Methods\n\nHere is the Ruby code:\n\n```ruby\n\n\n\nclass Person\n  attr_reader :name, :age\n  attr_writer :name, :age\n  def initialize(name, age)\n    @name = name\n    @age = age\n  end\nend\n\nperson = Person.new(\"Alice\", 30)\n\nperson.name # Returns \"Alice\"\nperson.name = \"Bob\" # Error: undefined method 'name='\n\nperson.age # Returns 30\nperson.age = 35 # Error: undefined method 'age='\n\nperson.instance_variables # Returns [:@name, :@age]\n\n```\n\u003cbr\u003e\n\n## 11. How does _garbage collection_ work in _Ruby_?\n\n**Ruby** employs automatic memory management, which is primarily influenced by **garbage collection techniques**. Let's understand the specifics.\n\n### Mark-and-Sweep Algorithm\n\n- **Step 1 - Mark**: The process starts from the **root** of object references. The GC traverses memory, marking referenced objects.\n  \n- **Step 2 - Sweep**: It scans for **unmarked** objects and reclaims their memory, making it available for future use.\n\n### Generational Garbage Collection\n\nTo optimize the Mark-and-Sweep approach, Ruby introduces generational garbage collection.\n\n- **Focused on Object Age**: Objects are classified based on their age.\n\n- **Young vs. Old Objects**: \n  - New objects start in the **Young Generation**.\n  - Objects that persist multiple GC cycles move to the **Old Generation**.\n\n- **Collection Frequency**: The Young Generation is collected more frequently.\n\n- **Short- and Long-Lived Object Management**: It's easier to collect younger objects, reducing the scope and overhead of a complete garbage collection cycle.\n\n### Reference-Counting and `ObjectSpace`\n\nAlthough CPython uses reference-counting to track object lifespans, Ruby typically does not. \n\n- **ObjectSpace**: It's a module that allows retrieval of all objects.\n\n  However, note that modern Ruby versions represent a hybrid system, sensitive to object types and context.\n\n### Code Example: Garbage Collection in Ruby\n\nHere is the Ruby code:\n\n```ruby\n# Enable trashcan (Ruby 2.6 onwards)\nObjectSpace::count_objects[:FREE] \u003e 100_000 \u0026\u0026 GC.start\n\n# Ruby versions before 2.6\nGC.start\n```\n\u003cbr\u003e\n\n## 12. Explain the difference between '_gets.chomp_' and '_gets.strip_'.\n\nLet me go through the major difference.\n\n### Key Distinctions\n\n- **Input Requirement**:\n  - `gets.chomp` removes **all trailing whitespace** and the newline character.\n  - `gets.strip` eliminates **all leading and trailing whitespace**, including the newline character.\n\n- **Use Cases**:\n  - **`gets.chomp`**: Suited when you anticipate or require specific trailing characters to be preserved.\n  - **`gets.strip`**: Ideal for scenarios where you need to sanitize or validate user input by removing any extra leading or trailing spaces.\n\n### Code Sample: `gets.chomp` \u0026 `gets.strip`\n\nHere is the Ruby code:\n\n```ruby\n# Using the gets.chomp method\nputs \"Enter your name (including a trailing space): \"\nname_chomp = gets.chomp\nputs \"Name with trailing space: #{name_chomp}\"\n\n# Using the gets.strip method\nputs \"Enter your name: \"\nname_strip = gets.strip\nputs \"Name without trailing space: #{name_strip}\"\n```\n\u003cbr\u003e\n\n## 13. What is the role of '_self_' in _Ruby_?\n\nIn Ruby, **`self`** serves as a \"mirror\" that reflects the current context. Depending on where it's used, `self` can represent different objects.\n\nHere's the breakdown:\n\n### `Self` in Different Contexts\n\n#### 1. Instance Methods\n\nIn this context, `self` refers to the instance of the object on which the method is called.\n\nConsider the following code:\n\n```ruby\nclass MyClass\n  def instance_method\n    puts self\n  end\nend\n\nobject = MyClass.new\nobject.instance_method\n```\n\nThe output would be the object reference `#\u003cMyClass:0x007fb4fa869358\u003e`.\n\n#### 2. Class Methods\n\nWithin a class definition, `self` refers to the class itself. This is why you use `self.method_name` to define class methods.\n\nFor instance:\n\n```ruby\nclass MyClass\n  def self.class_method\n    puts self\n  end\nend\n\nMyClass.class_method\n```\n\nThe output will be the class `MyClass`.\n\n#### 3. Method Invocation\n\nWhen a method is missing due to a typo or other reason, Ruby executes `method_missing` which can help handle such cases.\n\nConsider this example:\n\n```ruby\nclass MyClass\n  def method_missing(m, *args)\n    puts \"There's no method called #{m}\"\n  end\n\n  def test_method\n    method_thaat_doesnt_exist\n  end\nend\n```\n\nCalling `test_method` will invoke `method_missing` with the method name `\"method_thaat_doesnt_exist\"`.\n\u003cbr\u003e\n\n## 14. Explain the principle of '_Convention over Configuration_' in the context of _Ruby_.\n\n**Convention over Configuration** (CoC) is a software design principle that simplifies development by reducing the number of decisions developers need to make.\n\nIn its essence, CoC means that frameworks come with **best practice defaults** or \"conventions\" that are automatically applied unless explicitly configured to behave differently.\n\n### Practical Application\n\n1. **Code-Base Structures**: Many Ruby web frameworks, like Ruby on Rails or Sinatra, expect a certain directory structure that groups related files.\n2. **Naming Conventions**: Specially designed rules for naming classes, methods, and databases to help in identification and automatic linking.\n3. **API Endpoints**: Through consistent naming, it's possible to infer routing information in web applications.\n4. **Database Schemas**: Named fields and tables allow the ORM to deduce relationships and configurations.\n\n### Example: CRUD Actions in RoR\n\nIn Ruby on Rails, the \"conventions\" for a resourceful route automatically map HTTP verbs to CRUD actions:\n\n```ruby\n# config/routes.rb\nresources :articles\n\n# Routes:\n# HTTP   Path                Controller#Action    Used For\n# ------------------------------------------------------------\n# GET    /articles           articles#index       Display a list\n# GET    /articles/:id       articles#show        Display a specific article\n# GET    /articles/new       articles#new         Display a form to create a new article\n# POST   /articles           articles#create      Add a new article to the database\n# GET    /articles/:id/edit  articles#edit        Display a form to edit an existing article\n# PATCH  /articles/:id       articles#update      Update an existing article in the database\n# PUT    /articles/:id       articles#update      (Alternate for update)\n# DELETE /articles/:id       articles#destroy     Remove a specific article from the database\n```\n\nHere, the convention to map action names to routes frees the developer from configuring each route manually.\n\n### Benefits\n\n- **Speed**: It streamlines development and reduces boilerplate.\n- **Interoperability**: CoC enables consistency across different projects and teams.\n\n### Risks and Challenges\n\n- **Over-optimization**: While it's efficient for simple, well-understood requirements, it can make advanced configurations and customizations cumbersome.\n- **Learning Curve**: Newcomers might find it challenging to adapt to these standard conventions.\n- **Magic**: Over-reliance on CoC can make the system seem like it has hidden, unexplained behaviors.\n\u003cbr\u003e\n\n## 15. How does _Ruby_ support _metaprogramming_?\n\n**Ruby** offers powerful **metaprogramming** capabilities, enabling developers to write flexible, dynamic code. Key to Ruby's metaprogramming are `class` methods such as `define_method` and language features like `Open Classes` leading to advanced techniques like `Dynamic Dispatch`.\n\n### Dynamic Dispatch Mechanism\n\n- **Dynamic Dispatch**: Methods can be called at runtime, based on the object's context, using `send`. This makes it easier to manage method invocations in metaprogrammed code.\n\n```ruby\nclass MathOperations\n  def do_operation(operator, x, y)\n    send(operator, x, y) # Dynamic dispatch\n  end\n\n  private\n\n  def add(x, y)\n    x + y\n  end\n\n  def subtract(x, y)\n    x - y\n  end\nend\n\nresult = MathOperations.new.do_operation(:add, 10, 5) # 15\n```\n\n### Class Modifications with `Open Classes`\n\n- **Open Classes**: Ruby allows changing a class's definition dynamically, even after its initial declaration.\n  \n  This example adds a `reverse` method to the `String` class.\n\n  ```ruby\n  class String\n    def reverse\n      chars.reverse.join\n    end\n  end\n  ```\n\n### Code Evaluation and Execution\n\n- **Code Evaluation**: Code strings can be executed within a bound context, enabling runtime code execution and evaluation.\n\n  This is an example using `eval` to define a method at runtime, equivalent to `def double(x) x * 2; end`, but the method signature is constructed dynamically.\n\n  ```ruby\n  method_signature = 'double(x)'\n  method_body = 'x * 2'\n  eval(\"def #{method_signature}; #{method_body}; end\")\n  ```\n\n- **Binding Tasks**: `proc` objects capture both the method (or block) and its associated context. They can be transferred across lexical scopes, allowing delayed execution of code.\n\n  ```ruby\n  context = binding\n  task = Proc.new { eval 'some_method', context }\n  ```\n\n- **Context Toggling**: By toggling a method's visibility, you can control its access scope.\n\n  ```ruby\n  class MyClass\n    def some_method\n      \"Public method\"\n    end\n\n  private\n\n    def toggle_method_visibility(visibility)\n      # `send` here is being used for dynamic dispatch\n      send(visibility, :some_method)\n    end\n  end\n\n  instance = MyClass.new\n  instance.toggle_method_visibility(:private)\n  ```\n\n### Internationalization: Advanced Use of `send` and `eval`\n\n- **Localizing Method Calls**: In internationalization tasks where method calls need to be localized, `send`, `public_send`, or even the more general `eval` can be suitable.\n\n  ```ruby\n  def greeting(language)\n    eval(\"#{language}_greeting\")\n  end\n\n  def spanish_greeting\n    \"Hola Mundo\"\n  end\n  ```\n\n### Method Missing and Missing Method Feature\n\n- **Method Missing**: This feature is the heart of Ruby's duck typing. It allows classes and objects to respond to method calls even when their definitions are absent, rather than resorting to method-not-found errors.\n\n  This example cleans up a method call, removing spaces or underscores.\n\n  ```ruby\n  def method_missing(name, *args, \u0026block)\n    cleaned_name = name.to_s.delete(' ').delete('_')\n    send(cleaned_name, *args, \u0026block)\n  end\n  ```\n\n- **`respond_to_missing?`**: This method is often used in conjunction with `method_missing`, providing a way for a class to communicate whether it handles a method call beyond what is statically defined.\n\u003cbr\u003e\n\n\n\n#### Explore all 100 answers here 👉 [Devinterview.io - Ruby](https://devinterview.io/questions/web-and-mobile-development/ruby-interview-questions)\n\n\u003cbr\u003e\n\n\u003ca href=\"https://devinterview.io/questions/web-and-mobile-development/\"\u003e\n\u003cimg src=\"https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/github-blog-img%2Fweb-and-mobile-development-github-img.jpg?alt=media\u0026token=1b5eeecc-c9fb-49f5-9e03-50cf2e309555\" alt=\"web-and-mobile-development\" width=\"100%\"\u003e\n\u003c/a\u003e\n\u003c/p\u003e\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdevinterview-io%2Fruby-interview-questions","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdevinterview-io%2Fruby-interview-questions","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdevinterview-io%2Fruby-interview-questions/lists"}