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...endor{...}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.
yieldis 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.newor theprocmethod.
- 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
lambdamethod 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
classkeyword 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
defkeyword 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
nilandfalsein Ruby?- Both
nilandfalserepresent false values in Ruby, butnilis used to denote the absence of a value or an uninitialized state, whilefalseis 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
includeorextendkeywords, 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...endblocks. You can also useensureto 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
initializemethod in Ruby?- The
initializemethod 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
includeandextendin Ruby?includeadds the module’s methods as instance methods to the class, whileextendadds them as class methods.
- Explain the
attr_accessormethod in Ruby.attr_accessoris 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_readercreates only a getter method,attr_writercreates only a setter method, andattr_accessorcreates 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
selfkeyword in Ruby?selfrefers 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
defkeyword 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
requireandrequire_relative?requireis used to load external libraries or files using an absolute path or from the load path, whilerequire_relativeloads 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
Enumeratorclass or by callingto_enumorenum_foron 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
mapmethod in Ruby?- The
mapmethod 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
selectmethod do in Ruby?- The
selectmethod returns an array containing all elements of an enumerable for which the block returns a true value.
- The
- Explain the difference between
to_sandto_strin Ruby.to_sis a method used to convert an object to a string, whileto_stris 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
popandshiftin Ruby?popremoves and returns the last element of an array, whileshiftremoves and returns the first element.
- Explain what the
freezemethod does in Ruby.- The
freezemethod 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=beginand=end.
- Single-line comments start with
- What is the
superkeyword in Ruby?- The
superkeyword 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
privatekeyword. They cannot be called with an explicit receiver.
- Private methods are defined within a class using the
- What is the difference between
putsandprintin Ruby?putsadds a newline after printing the message, whileprintdoes not.
- How do you open a file in Ruby?
- A file can be opened using the
File.openmethod. Example:File.open('file.txt', 'r') do |file|
# process the file
end
- A file can be opened using the