Ruby Interview Questions:
- What is Ruby?
- Ruby is an open-source, dynamic, object-oriented programming language created by Yukihiro Matsumoto in the mid-1990s. It’s known for its simplicity and productivity, with an elegant syntax that is natural to read and easy to write.
- Explain what Ruby on Rails is.
- Ruby on Rails, often simply referred to as Rails, is a server-side web application framework written in Ruby. It follows the MVC (Model-View-Controller) architecture pattern and provides default structures for a database, a web service, and web pages.
- What are some key features of Ruby?
- Some key features include:
- Purely object-oriented
- Simple and readable syntax
- Dynamic typing and duck typing
- Mixins (using modules)
- Exception handling
- Garbage collection
- Some key features include:
- What are the differences between Ruby and other programming languages like Python or Java?
- Ruby is more focused on simplicity and productivity with elegant syntax. Unlike Python, Ruby has more syntax flexibility, allowing for more freedom in code structure. Java is a statically typed language with a more verbose syntax, while Ruby is dynamically typed.
- What is IRB in Ruby?
- IRB stands for Interactive Ruby. It is a REPL (Read-Eval-Print Loop) environment for programming in Ruby, allowing you to execute Ruby code in a real-time interactive session.
- What is a Ruby gem?
- A Ruby gem is a packaged Ruby application or library that can be shared and installed through the RubyGems package manager. It makes it easy to distribute and manage dependencies.
- How do you install a gem in Ruby?
- You can install a gem using the command:
gem install <gem_name>
- You can install a gem using the command:
- What is a block in Ruby?
- A block is a chunk of code enclosed between
do...end
or{...}
that you can pass to methods like an argument. Blocks can be called within methods usingyield
.
- A block is a chunk of code enclosed between
- Explain the concept of “yield” in Ruby.
yield
is used to transfer control from a method to the block that is passed to it. It allows you to execute a block of code within the context of a method.
- What is a Proc in Ruby?
- A Proc is an object that encapsulates a block of code, which can be stored in a variable and passed around like any other object. You can create a Proc using
Proc.new
or theproc
method.
- A Proc is an object that encapsulates a block of code, which can be stored in a variable and passed around like any other object. You can create a Proc using
- What is a lambda in Ruby?
- A lambda is a special type of Proc. It checks the number of arguments passed to it and returns control to the calling method when it executes a return statement. It is created using the
lambda
method or the->
syntax.
- A lambda is a special type of Proc. It checks the number of arguments passed to it and returns control to the calling method when it executes a return statement. It is created using the
- What are symbols in Ruby?
- Symbols are immutable, reusable constants represented with a colon and a name (e.g.,
:symbol
). They are often used as identifiers, keys in hashes, or for passing method names.
- Symbols are immutable, reusable constants represented with a colon and a name (e.g.,
- What is a Hash in Ruby?
- A Hash is a collection of key-value pairs, similar to a dictionary in Python. Keys are unique and can be of any data type, although symbols are commonly used.
- How do you create a class in Ruby?
- A class in Ruby is created using the
class
keyword followed by the class name. Example:class MyClass
# class body
end
- A class in Ruby is created using the
- What is an instance variable in Ruby?
- An instance variable is a variable that is accessible only within the context of a particular instance of a class. It is prefixed with an
@
symbol (e.g.,@variable
).
- An instance variable is a variable that is accessible only within the context of a particular instance of a class. It is prefixed with an
- How do you define a method in Ruby?
- Methods in Ruby are defined using the
def
keyword followed by the method name and optional parameters. Example:def my_method(param)
# method body
end
- Methods in Ruby are defined using the
- What is the difference between
nil
andfalse
in Ruby?- Both
nil
andfalse
represent false values in Ruby, butnil
is used to denote the absence of a value or an uninitialized state, whilefalse
is a boolean representing the logical false.
- Both
- Explain the concept of mixins in Ruby.
- Mixins allow you to share code among multiple classes using modules. Modules are included in classes using the
include
orextend
keywords, providing a way to achieve multiple inheritance.
- Mixins allow you to share code among multiple classes using modules. Modules are included in classes using the
- How do you handle exceptions in Ruby?
- Exceptions in Ruby are handled using
begin...rescue...end
blocks. You can also useensure
to execute code that should run regardless of whether an exception occurred. Example:begin
# code that might raise an exception
rescue SomeExceptionClass => e
# code to handle the exception
ensure
# code that will always run
end
- Exceptions in Ruby are handled using
- What is the purpose of the
initialize
method in Ruby?- The
initialize
method is a special method in Ruby that is called automatically when a new instance of a class is created. It is typically used to set up initial values for instance variables.
- The
- What is a module in Ruby?
- A module is a collection of methods and constants. Modules are used for namespacing and as mixins to add functionality to classes without using inheritance.
- What is the difference between
include
andextend
in Ruby?include
adds the module’s methods as instance methods to the class, whileextend
adds them as class methods.
- Explain the
attr_accessor
method in Ruby.attr_accessor
is a method that creates both getter and setter methods for instance variables. It is a shorthand for defining these methods manually.
- What is the difference between
attr_reader
,attr_writer
, andattr_accessor
?attr_reader
creates only a getter method,attr_writer
creates only a setter method, andattr_accessor
creates both getter and setter methods.
- What is a class variable in Ruby?
- A class variable is shared among all instances of a class and is prefixed with
@@
. It is used to store class-level information.
- A class variable is shared among all instances of a class and is prefixed with
- What is the scope of a local variable in Ruby?
- Local variables are accessible only within the context they are defined, such as within a method, block, or loop.
- What is the purpose of the
self
keyword in Ruby?self
refers to the current object instance and is used to access its methods and variables.
- How do you create a subclass in Ruby?
- A subclass is created using the
<
symbol followed by the name of the superclass. Example:class SubClass < SuperClass
# subclass body
end
- A subclass is created using the
- Explain the concept of method overriding in Ruby.
- Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.
- What is a singleton method in Ruby?
- A singleton method is a method that is defined for a single instance of a class rather than for all instances. It is defined using the
def
keyword followed by the object and method name.
- A singleton method is a method that is defined for a single instance of a class rather than for all instances. It is defined using the
- How do you define a constant in Ruby?
- Constants in Ruby are defined by assigning a value to a name that starts with an uppercase letter. Example:
CONSTANT_NAME = 'constant value'
- Constants in Ruby are defined by assigning a value to a name that starts with an uppercase letter. Example:
- What is the difference between
require
andrequire_relative
?require
is used to load external libraries or files using an absolute path or from the load path, whilerequire_relative
loads a file relative to the file in which it is called.
- What are enumerators in Ruby?
- Enumerators provide an external iterator over a collection and allow iteration in different ways. They are created using the
Enumerator
class or by callingto_enum
orenum_for
on a collection.
- Enumerators provide an external iterator over a collection and allow iteration in different ways. They are created using the
- How do you iterate over a hash in Ruby?
- You can iterate over a hash using methods like
each
,each_key
,each_value
, oreach_pair
. Example:hash.each do |key, value|
puts "#{key}: #{value}"
end
- You can iterate over a hash using methods like
- What is the purpose of the
map
method in Ruby?- The
map
method creates a new array containing the results of running a block once for every element in the array it is called on.
- The
- What does the
select
method do in Ruby?- The
select
method returns an array containing all elements of an enumerable for which the block returns a true value.
- The
- Explain the difference between
to_s
andto_str
in Ruby.to_s
is a method used to convert an object to a string, whileto_str
is a stricter method intended for objects that can be considered as strings.
- How do you create an array in Ruby?
- An array can be created using square brackets with comma-separated values. Example:
array = [1, 2, 3, 4, 5]
- An array can be created using square brackets with comma-separated values. Example:
- What is the difference between
pop
andshift
in Ruby?pop
removes and returns the last element of an array, whileshift
removes and returns the first element.
- Explain what the
freeze
method does in Ruby.- The
freeze
method prevents an object from being modified. Once an object is frozen, any attempts to modify it will raise a runtime error.
- The
- What is a range in Ruby?
- A range represents a sequence of values and is created using the
..
or...
operators. Example:range = 1..10 # includes 10
range = 1...10 # excludes 10
- A range represents a sequence of values and is created using the
- How do you check if a value is included in a range?
- You can check if a value is included in a range using the
include?
method. Example:(1..10).include?(5) # returns true
- You can check if a value is included in a range using the
- What is a mixin in Ruby?
- A mixin is a module included in a class to add functionality. It allows sharing code among different classes without using inheritance.
- Explain the concept of polymorphism in Ruby.
- Polymorphism in Ruby allows objects of different classes to respond to the same method call. It is typically achieved through duck typing, where the type of the object is determined by its methods and properties rather than its class.
- What is metaprogramming in Ruby?
- Metaprogramming is a programming technique where code can write or modify other code at runtime. Ruby supports metaprogramming through features like
eval
,define_method
, andclass_eval
.
- Metaprogramming is a programming technique where code can write or modify other code at runtime. Ruby supports metaprogramming through features like
- How do you comment code in Ruby?
- Single-line comments start with
#
, and multi-line comments are enclosed between=begin
and=end
.
- Single-line comments start with
- What is the
super
keyword in Ruby?- The
super
keyword is used to call the same method from the superclass within the context of a subclass method.
- The
- How do you define a private method in Ruby?
- Private methods are defined within a class using the
private
keyword. They cannot be called with an explicit receiver.
- Private methods are defined within a class using the
- What is the difference between
puts
andprint
in Ruby?puts
adds a newline after printing the message, whileprint
does not.
- How do you open a file in Ruby?
- A file can be opened using the
File.open
method. Example:File.open('file.txt', 'r') do |file|
# process the file
end
- A file can be opened using the