Ruby Interview Questions and Answers
-
What is Ruby?
- Answer: Ruby is a dynamic, reflective, object-oriented, general-purpose programming language. It's known for its elegant syntax and emphasis on developer happiness.
-
What is a class in Ruby?
- Answer: A class is a blueprint for creating objects. It defines the attributes (data) and methods (behavior) that objects of that class will have.
-
What is an object in Ruby?
- Answer: An object is an instance of a class. It's a concrete realization of the blueprint defined by the class.
-
Explain the difference between `=` and `==` in Ruby.
- Answer: `=` is the assignment operator (assigns a value to a variable). `==` is the equality operator (compares two objects for equality).
-
What are methods in Ruby?
- Answer: Methods are blocks of code that perform specific tasks. They define the behavior of objects.
-
What are symbols in Ruby?
- Answer: Symbols are unique, immutable objects often used as keys in hashes. They are more memory-efficient than strings.
-
What are blocks in Ruby?
- Answer: Blocks are anonymous functions that can be passed to methods. They are defined using `do...end` or `{}`.
-
What are iterators in Ruby?
- Answer: Iterators are methods that traverse a collection (like an array) and apply a block of code to each element.
-
Explain the difference between `each` and `map` in Ruby.
- Answer: `each` iterates through a collection and performs an action on each element without modifying the original collection. `map` iterates and transforms each element, returning a new collection with the transformed elements.
-
What are modules in Ruby?
- Answer: Modules are namespaces that group related constants, classes, and methods. They support code reuse and organization.
-
What is inheritance in Ruby?
- Answer: Inheritance allows a class (subclass or child class) to inherit attributes and methods from another class (superclass or parent class).
-
What is polymorphism in Ruby?
- Answer: Polymorphism allows objects of different classes to respond to the same method call in their own specific way.
-
What is encapsulation in Ruby?
- Answer: Encapsulation bundles data (attributes) and methods that operate on that data within a class, hiding internal details and protecting data integrity.
-
What is a mixin in Ruby?
- Answer: A mixin is a module included into a class to add functionality without using inheritance. It allows multiple inheritance-like behavior.
-
Explain the difference between `attr_reader`, `attr_writer`, and `attr_accessor`.
- Answer: `attr_reader` creates a getter method, `attr_writer` creates a setter method, and `attr_accessor` creates both getter and setter methods for an instance variable.
-
What are exceptions in Ruby?
- Answer: Exceptions are events that disrupt the normal flow of program execution. They are handled using `begin...rescue...end` blocks.
-
Explain the purpose of `begin...rescue...end` blocks.
- Answer: These blocks handle exceptions. The `begin` block contains the code that might raise an exception, `rescue` handles the exception, and `ensure` (optional) executes code regardless of whether an exception occurred.
-
What is the purpose of `raise` in Ruby?
- Answer: `raise` is used to explicitly throw an exception.
-
What is garbage collection in Ruby?
- Answer: Ruby uses automatic garbage collection to reclaim memory occupied by objects that are no longer referenced.
-
What is a metaclass in Ruby?
- Answer: A metaclass is a class's class. It defines the class's behavior and properties.
-
What is the difference between `self` and `this` in Ruby (or why is there no `this`)?
- Answer: Ruby uses `self` to refer to the current object within a method. There's no `this` keyword because `self` is implicitly understood within the context of the method.
-
How do you define a constant in Ruby?
- Answer: Constants are defined using uppercase names (e.g., `MY_CONSTANT = 10`). While not strictly enforced, it's a convention to indicate that a variable should not be reassigned.
-
What are lambdas in Ruby?
- Answer: Lambdas are anonymous functions similar to blocks, but they are objects and can be assigned to variables.
-
What is the difference between a lambda and a proc?
- Answer: Both are anonymous functions, but lambdas check the number of arguments passed, while procs do not. Lambdas return from themselves, while procs return from the calling method.
-
What are some common Ruby frameworks?
- Answer: Ruby on Rails, Sinatra, Hanami are some popular frameworks.
-
What is RubyGems?
- Answer: RubyGems is a package manager for Ruby libraries and applications.
-
How do you install a gem?
- Answer: Use the command `gem install gem_name`.
-
What is Bundler?
- Answer: Bundler manages a project's dependencies as specified in a Gemfile.
-
How do you create a new Rails application?
- Answer: Use the command `rails new app_name`.
-
What are ActiveRecord models in Rails?
- Answer: ActiveRecord models represent database tables and provide an interface for interacting with the database.
-
What are controllers in Rails?
- Answer: Controllers handle user requests and interact with models to manage data.
-
What are views in Rails?
- Answer: Views render the user interface, displaying data from the models and controllers.
-
What is MVC architecture?
- Answer: Model-View-Controller is a software design pattern separating application concerns into models (data), views (UI), and controllers (logic).
-
What is RESTful design?
- Answer: RESTful design is an architectural style for creating web services using standard HTTP methods (GET, POST, PUT, DELETE).
-
What is a gemspec file?
- Answer: A gemspec file describes a RubyGem, containing metadata like name, version, dependencies, and more.
-
What is the difference between `puts` and `print`?
- Answer: `puts` adds a newline character after printing, while `print` does not.
-
How do you comment code in Ruby?
- Answer: Use `#` for single-line comments and `=begin...=end` for multi-line comments.
-
What is the purpose of `require` and `include`?
- Answer: `require` loads a Ruby file, while `include` incorporates a module's methods into a class.
-
What is the difference between `instance_variable_get` and `instance_variable_set`?
- Answer: `instance_variable_get` retrieves the value of an instance variable, while `instance_variable_set` sets its value.
-
How do you create a new array in Ruby?
- Answer: `my_array = []` or `my_array = Array.new` or `my_array = [1, 2, 3]`
-
How do you create a new hash in Ruby?
- Answer: `my_hash = {}` or `my_hash = Hash.new` or `my_hash = { "a" => 1, "b" => 2 }`
-
Explain Ruby's `nil` value.
- Answer: `nil` represents the absence of a value. It's similar to `null` in other languages.
-
What is a singleton method in Ruby?
- Answer: A singleton method is a method defined only for a specific object instance.
-
What is the purpose of the `yield` keyword?
- Answer: `yield` passes control to the block associated with a method call.
-
How do you handle multiple exceptions in a `rescue` block?
- Answer: Use multiple `rescue` clauses, or a single `rescue` with a list of exception classes.
-
What is the difference between `String#gsub` and `String#sub`?
- Answer: `gsub` replaces all occurrences of a pattern, while `sub` replaces only the first occurrence.
-
How do you access the last element of an array?
- Answer: `my_array[-1]`
-
How do you check if an array is empty?
- Answer: `my_array.empty?`
-
What is the purpose of `to_s`?
- Answer: `to_s` converts an object to its string representation.
-
What is the purpose of `to_i`?
- Answer: `to_i` converts an object to an integer.
-
What is the purpose of `to_f`?
- Answer: `to_f` converts an object to a floating-point number.
-
What is the difference between `Object#dup` and `Object#clone`?
- Answer: `dup` creates a shallow copy, while `clone` creates a deep copy (considering frozen objects and singletons).
-
What is the `freeze` method?
- Answer: `freeze` makes an object immutable, preventing further modifications.
-
Explain Ruby's `tap` method.
- Answer: `tap` yields the receiver to a block and then returns the receiver.
-
What is the purpose of `times` method?
- Answer: `times` iterates a specified number of times.
-
What is the purpose of `upto` method?
- Answer: `upto` iterates from the receiver up to a specified value.
-
What is the purpose of `downto` method?
- Answer: `downto` iterates from the receiver down to a specified value.
-
What is the `step` method used for?
- Answer: `step` iterates with a specified increment.
-
Explain Ruby's `inject` method.
- Answer: `inject` (or `reduce`) combines elements of an array using a given operation.
-
What is the difference between `puts` and `p`?
- Answer: `puts` prints a value, while `p` prints a value and its inspected representation (useful for debugging).
-
What is a symbol's advantage over a string?
- Answer: Symbols are unique and immutable, making them memory-efficient and suitable for hash keys.
-
How can you create a range in Ruby?
- Answer: `(1..5)` (inclusive) or `(1...5)` (exclusive).
-
What is the `each_with_index` method used for?
- Answer: `each_with_index` iterates through a collection, providing both the element and its index.
-
How do you check if a string contains a substring?
- Answer: `my_string.include?("substring")`
-
How do you convert a string to uppercase?
- Answer: `my_string.upcase`
-
How do you convert a string to lowercase?
- Answer: `my_string.downcase`
-
How do you split a string into an array of words?
- Answer: `my_string.split`
-
What is the purpose of regular expressions in Ruby?
- Answer: Regular expressions provide a powerful way to search and manipulate strings based on patterns.
-
How do you define a regular expression in Ruby?
- Answer: Using forward slashes (e.g., `/pattern/` or `Regexp.new("pattern")`)
-
What is the `match` method for regular expressions?
- Answer: `match` attempts to match a regular expression against a string.
-
What is the `scan` method for regular expressions?
- Answer: `scan` finds all occurrences of a regular expression in a string.
-
What are some common regular expression metacharacters?
- Answer: `^`, `$`, `*`, `+`, `?`, `.`, `[]`, `()`, `{}`, `|`, `\`. (Many more exist depending on the flavor of regex.)
-
Explain Ruby's `__FILE__` constant.
- Answer: `__FILE__` contains the path of the currently executing file.
Thank you for reading our blog post on 'Ruby Interview Questions and Answers'.We hope you found it informative and useful.Stay tuned for more insightful content!