RUBY programing interview question set 1/Ruby Interview Questions and Answers for Freshers & Experienced

What is the difference between Array#map and Array#each?

Array#each method iterates over the elements of the array and executes the provided block each time. However, it returns the original array unaffected.

Array#map will return a new array of elements containing the values returned by the block it is provided. It also does not affect the original array

What is a PORO?

PORO stands for “Plain Old Ruby Object”.
Although almost everything in Ruby is an object, ActiveRecord tends to use a lot of complex objects. So, the term PORO is typically to stress a small, simple object used to support business logic.

What is the meaning of “skinny controllers, skinny models”?

As a codebase grows, fat models get out of hand, start doing too many things and become unmanageable. Models should handle persistence without being bloated with logic.
Models can be made skinnier by keeping the single responsibility principle in mind and moving logic out of models, and into other design patterns like service objects.

What is the meaning of “Fat models, skinny controllers”?

Business logic should exist in models, not controllers. This makes logic easier to unit test and is more re-usable.
Controllers are merely the hands that pass information between views and models.
This is generally given as advice to new Rails developers. It’s not actually recommended, particularly in large apps.

Explain Each iterator?

Iterators are methods that naturally loop over a given set of data and allow you to operate on each element in the collection. Each iterator pulls out each element of a container or an array and assigns to the variable. Using the value of the variable, we can do our desired operation.


[1,2,3].each { |s|
puts s
#=> 1,2,3

What is the difference between delete and destroy?

delete: Deletes a record.

destroy: Deletes a record and executes callbacks.

What are initializers in Rails?

Initializers hold configuration logic and only run when an app is booted. This means the Rails server needs to be restarted if initializers are changed. They exist in the /config/initializers directory.

What Is The Difference Between A Class And A Module?

A module cannot be subclassed or instantiated, and modules can implement mixins.

What Are The Three Levels Of Method Access Control For Classes And What Do They Signify? What Do They Imply About The Method?

Public, protected, and private.

Public methods can be called by all objects and subclasses of the class in which they are defined in.
Protected methods are only accessible to objects within the same class.
Private methods are only accessible within the same instance.

How Would You Create Getter And Setter Methods In Ruby?

Setter and getter methods in Ruby are generated with the attr_accessor method. attr_accessor is used to generate instance variables for data that’s not stored in your database column.

You can also take the long route and create them manually.

What is the difference between #== and #equal??

#== performs the generic comparison and is implemented differently across classes while #equal? is defined on BasicObject and compares object identity. Therefore, #equal? should not be overridden in subclasses.

What Is The Difference Between Delete And Destroy?

The Delete method essentially deletes a row (or an array of rows) from the database.
Destroy on the other hand allows for a few more options. First, it will check any callbacks such as before_delete, or any dependencies that we specify in our model. Next, it will keep the object that just got deleted in memory; this allows us to leave a message saying something like " 'Object_name' has been deleted." Lastly, and most importantly, it will also delete any child objects associated with that object.

Explain about Loop keyword?

The simplest way to create a loop in Ruby is using the loop method. The loop takes a block, which is denoted by { ... } or do ... end. A loop will execute any code within the block until a break statement inside the block, which will force the loop to stop and the execution will continue after the loop.


loop do
break # this will cause execution to exit the loop

Explain about Until loop in Ruby?

Until loop is very similar to while loop. The only difference between while loop and until the loop is that while loop executes set of statements repeatedly until the condition becomes false and until loop executes set of statements repeatedly until the condition becomes true. Until is vice versa of while.


until conditional [do]

Explain about While loop in Ruby?

While loop is used to execute a block or segment of code repeatedly until the condition becomes false. A while loop's conditional is separated from code by the reserved word 'do', a newline, backslash , or a semicolon.


while conditional [do]

Explain about For loop in Ruby?

The for loop consists of for followed by a variable to contain the iteration argument followed by in and the value to iterate over using each.


for variable [, variable ...] in expression [do]

Explain Loops in Ruby?

Loops are used to execute a set of statements repeatedly based on a condition. It is sometimes necessary to execute a set of statements again and again. Loops and iterators in Ruby are a great way to perform repeated operations on a data set. There are 5 types of loops are available in Ruby

<> For loop
<> While loop
<> Until loop
<> A simple Loop keyword

Mention What Is The Command To Create A Migration?

To create migration command includes

Explain How Can We Define Ruby Regular Expressions?

Ruby regular expression is a special sequence of characters that helps you match or find other strings. A regular expression literal is a pattern between arbitrary delimiters or slashes followed by %r.

List Out The Few Features Of Ruby?

Free format – You can start writing from program from any line and column.
Case sensitive – The uppercase and lowercase letters are distinct.
Comments – Anything followed by an unquoted #, to the end of the line on which it appears, is ignored by the interpreter.
Statement delimiters- Multiple statements on one line must be separated by semicolons, but they are not required at the end of a line.

Mention What Is The Difference Between Procs And Blocks?

The difference between Procs and Blocks,

>> Block is just the part of the syntax of a method while proc has the characteristics of a block.
>> Procs are objects, blocks are not.
>> At most one block can appear in an argument list.
>> Only block is not able to be stored into a variable while Proc can.

Explain About The Command Line Options?

Ruby`s language is executed from the command line like most of the scripting languages. Programming and behavior language environment can be controlled from the interpreter itself. Some of the commands which are used are as follows –d, -h, -e prog, -v, -T, -r lib, etc.

Explain About Operators In Ruby?

Like all the modern languages Ruby supports many different operators to its credit. Most of the operators in Ruby are in fact methods due to the object oriented nature of the language. This feature gives Ruby an edge over its competitors. Semantics of these operators can be changed due to the object oriented nature of the language.

Explain About The Defined Operator?

Define operator defines whether a passed expression is defined or not. If the expression is defined it returns the description string or null if the expression is not defined. If a variable is defined it gets initialized. If method_call is defined as true then method also gets defined. This is also the same case with super and yield.

Mention what is the difference between the Observers and Callbacks in Ruby on Rails?

Rails Observers: Observers is same as Callback, but it is used when method is not directly associated to object lifecycle. Also, the observer lives longer, and it can be detached or attached at any time. For example, displaying values from a model in the UI and updating model from user input.

Rails Callback: Callbacks are methods, which can be called at certain moments of an object’s life cycle for example it can be called when an object is validated, created, updated, deleted, A call back is short lived. For example, running a thread and giving a call-back that is called when thread terminates

Explain The Difference Between Nil And False In Ruby.

The differences of the methods nil and false are:

1. nil cannot be a value, where as a false can be a value.
2. A method returns true or false in case of a predicate, other wise nil is returned.
3. false is a boolean data type, where as nil is not.
4. nil is an object for NilClass, where as false is an object of for FalseClass

Mention what is the difference between calling super() and super call?

super(): A call to super() invokes the parent method without any arguments, as presumably expected. As always, being explicit in your code is a good thing.

super call: A call to super invokes the parent method with the same arguments that were passed to the child method. An error will therefore occur if the arguments passed to the child method don’t match what the parent is expecting.

How does Ruby on Rails use the Model View Controller (MVC) framework?

Web development can often be divided into three separate but closely integrated subsystems:

>> Model (Active Record): The model handles all the data logic of the application. In Rails, this is handled by the Active Record library, which forms the bridge between the Ruby program code and the relational database.
>> View (Action View): The view is the part of the application that the end user sees. In Rails, this is implemented by the Action View library, which is based on Embedded Ruby (ERB) and determines how data will be presented.
>> Controller (Action Controller): The controller is like the data broker of an application, handling the logic that allows the model and view to communicate with one another. This is called the Action Controller in Rails.

Explain About Normal Method Class?

This function calls a method and it can take any number of arguments and expr. Make sure that you put an asterisk or an ampersand before the expression. Last expr argument can be declared with a hash without any braces. If you want to increase the size of the array value then make sure that you put an asterisk before expression. “::” can be used to separate the class from methods.

Explain About Class Variable And Global Variable?

A class variable starts with an @@ sign which is immediately followed by upper or lower case letter. You can also put some name characters after the letters which stand to be a pure optional. A class variable can be shared among all the objects of a class. A single copy of a class variable exists for each and every given class.

To write a global variable you start the variable with a $ sign which should be followed by a name character. Ruby defines a number of global variables which also include other punctuation characters such as $_ and $-k.

When would you use a before_save vs. after_save callback?

Updating an object after it’s been saved requires an additional database transaction to persist the update. So, if you are updating an object’s attribute, a before_save callback is more efficient.

But sometimes information does exist on the object until it’s persisted (i.e.: id). So, if an id is required to create an associated record, that would have to be performed in an after_save callback.

What are callbacks?

“Callback” is a misleading term. They are hooks into the object lifecycle on which you can execute methods.
A number of callbacks exist around creating, updating, and destroying an object such as before_validation, after_save, and after_destroy.
They are useful for conditional logic like creating an associated Contact record when a User record is created.

Explain Conditional Statements in Ruby

Authorization (not to be confused with authentication) pertains to allowing different types of users different levels of access in an app. It’s useful when there are lots of types of users with differing levels of access.

How have you implemented authorization in the past?

Authorization (not to be confused with authentication) pertains to allowing different types of users different levels of access in an app. It’s useful when there are lots of types of users with differing levels of access.

What is the difference between count, length, and size?

<> count: Executes an SQL query to count the number of records. This is useful if the number of records may have changed in the DB vs. memory.
<> length: Returns the number of items in a collection in memory. It’s lighter weight than count because no database transaction is performed. It can also be used to count characters in a string.
<> size: This is an alias for length and does the same thing.

What are some Rails design patterns you’ve used?

There are a number of design patterns in Rails including service objects, value objects, form objects, query objects, view objects, policy objects, and decorators.

What is Gemfile.lock?

It contains records of exact versions of gems installed. This is so the same versions can be installed if another machine clones the project.
In contrast, specifying a gem in a Gemfile without pegging to a specific version will just install the latest version of a gem.

What is a Gemfile?

A Gemfile is where we specify dependencies for a Ruby application. It is located in the project’s root directory.

Describe a closure in Ruby

A closure is an object that is both an invocable function together with a variable binding. The object retains access to the local variables that were in scope at the time of the object definition.

A closure in Ruby retain variables by reference; the closure also extends the lifetimes of its variables. A closure's reference to its variables is dynamically bound that means the values of the variables are resolved when the Proc object is executed.

It also possible to alter a closure. The binding of a closure can be altered using #binding.

Why might you use #each instead of for/in?

It's the "Ruby way" - an example of how Ruby defines methods that mimic natural language concepts. Iterator methods such as #each read more naturally. #each is a block so it defines a new variable scope. for/in depends on the existence of #each which implies that #each is a more fundamental aspect of the language.

What is the difference between an Instance Variable and a Class Variable?

A class variable is evaluated in reference to the class object created by the enclosing class definition while
an instance variable is evaluated in reference to self. Instance variables cannot be referenced outside of instance methods.

What Is The Use Of Global Variable $ In Ruby?

The global variable is declared in Ruby that you can access it anywhere within the application because it has full scope in the application. The global variables are used in Ruby with $ prepend.

What Is The Use Of Interpolation In Ruby?

Interpolation is a process of inserting a string into a literal. It is a very important process in Ruby. A string can be interpolated into a literal by placing a hash (#) within {} open and close brackets.

Explain About Float, Dig And Max?

1. Float class is used whenever the function changes constantly. It acts as a sub class of numeric. They represent real characters by making use of the native architecture of the double precision floating point.
2. Max is used whenever there is a huge need of Float.
3. Dig is used whenever you want to represent a float in decimal digits.

What Are The Different Environment Variables Present In The Ruby?

Following are the different environment variables present in the Ruby:


Explain About Garbage Collection Feature Of Ruby?

1. Garbage collection is a process of reclaiming the memory space. Ruby deletes unallocated and unused objects automatically. This feature can be controlled by applying proper syntax and program through ruby.

2. Ruby performs garbage collection automatically. Ruby is an object oriented language and every object oriented language tends to allocate many objects during execution of the program.

Mention What Is The Difference Between A Single Quote And Double Quote?

A single-quoted strings don’t process ASCII escape codes, and they don’t do string interpolation.

Mention What Is The Difference Between A Gem And A Plugin In Ruby?

1. Gem: A gem is a just ruby code. It is installed on a machine, and it’s available for all ruby applications running on that machine.

2. Plugin: Plugin is also ruby code, but it is installed in the application folder and only available for that specific application.

Why Ruby Is Known As A Language Of Flexibility?

Ruby is known as a language of flexibility because it facilitates its author to alter the programming elements. Some specific parts of the language can be removed or redefined. Ruby does not restrict the user. For example, to add two numbers, Ruby allows to use + sign or the word 'plus'. This alteration can be done with Ruby's built-in class Numeric.

What Is Ruby Programming Language?

Ruby is a dynamic, reflective, general purpose, open source programming language that focuses on simplicity and productivity. Ruby has a mixed features of Perl, small talk, Eiffel, Ada and Lisp. Ruby was designed to create a new language which makes a balance with the functionality of Imperative languages.

R4R Team
R4R provides Ruby Freshers questions and answers (Ruby Interview Questions and Answers) .The questions on website is done by expert team! Mock Tests and Practice Papers for prepare yourself.. Mock Tests, Practice Papers,RUBY programing interview question set 1,Ruby Freshers & Experienced Interview Questions and Answers,Ruby Objetive choice questions and answers,Ruby Multiple choice questions and answers,Ruby objective, Ruby questions , Ruby answers,Ruby MCQs questions and answers Java, C ,C++, ASP, C# ,Struts ,Questions & Answer, Struts2, Ajax, Hibernate, Swing ,JSP , Servlet, J2EE ,Core Java ,Stping, VC++, HTML, DHTML, JAVASCRIPT, VB ,CSS, interview ,questions, and answers, for,experienced, and fresher R4r provides Python,General knowledge(GK),Computer,PHP,SQL,Java,JSP,Android,CSS,Hibernate,Servlets,Spring etc Interview tips for Freshers and Experienced for Ruby fresher interview questions ,Ruby Experienced interview questions,Ruby fresher interview questions and answers ,Ruby Experienced interview questions and answers,tricky Ruby queries for interview pdf,complex Ruby for practice with answers,Ruby for practice with answers You can search job and get offer latters by studing .learn in easy ways .