Ruby on Rails Interview Questions and Answers

Hey guys, hope you’re having a fine day. Today, my post will be to help answer some of the most difficult technical interview questions; because, interviews can always be stressful even for job seeker who have attended countless interviews. I believe the best way to reduce the stress is to be prepared.

Here are some of the most frequently asked questions and how to answer them confidently.

What is agile development

A:Agile methodology is anadaptaive methodology, its people
Here are some of the other characteristices of the Agile
1. Delivery frequently.
2. Good ROI for client.
3. Test frequently.
4. Collaborative approach.
Agile methodology is on daily basis report. How much work we have completed on that day and how much work is still pending…it gives the clear picture but the req are not defined beforehanditself completely.. req will be changing….

Why Ruby on Rails?

A: There are lot of advantages of using Ruby on Rails(ROR)
1. DRY Principal
2. Convention over Configuration
3. Gems and Plugins
4. Scaffolding
5. Pure OOP Concept

What is MVC? and how it Works?
A: MVC tends for Model-View-Controller, used by many languages like PHP, Perl, Python etc. The flow goes like below image



for Example your url is something like this:


here users is your controller and new is your method, there must be a file in your views/users folder named new.html.erb, so once the submit button is pressed, User model or whatever defined in the rhtml form_for syntax, will be called and values will be stored into the database.

What is ORM in Rails?
A: ORM tends for Object-Relationship-Model, it means that your Classes are mapped to table in the database, and Objects are directly mapped to the rows in the table.

What is Ruby Gems?
A. Ruby Gem is a software package, commonly called a “gem”. Gem contains a packaged Ruby application or library. The Ruby Gems software itself allows you to easily download, install and manipulate gems on your system.

What is Gemfile and Gemfile.lock?
A. The Gemfile is where you specify which gems you want to use, and lets you specify which versions. The Gemfile.lock file is where Bundler records the exact versions that were installed. This way, when the same library/project is loaded on another machine, running bundle install will look at the Gemfile.lock and install the exact same versions, rather than just using the Gemfile and installing the most recent versions. (Running different versions on different machines could lead to broken tests, etc.) You shouldn’t ever have to directly edit the lock file.
Get more Explanations on Gem file here.

What is Active record

A-There are many reasons why Active Record is the smart choice
Simplified configuration and default assumptions (Convention over Configuration).
Associations among objects.
Automated mapping b/w tables and classes and b/w columns and attributes.
Data Validations.
Inheritance hierarchies.
Direct manipulation of data as well as schema objects.
Database abstraction through adapters.
Logging support.
Migration support.
Active Record integrated in other emerging frameworks like Merb.

How you run your Rails application without creating databases?
A. You can run your application by uncommenting the line in environment.rb
path=> rootpath conf/environment.rb
config.frameworks- = [action_web_service, :action_mailer, :active_record

What are the servers supported by ruby on rails?
A. Ruby Supports a number of Rails servers (Mongrel, WEBRICK, PHUSION, Passenger, etc..depending on the specific platforms).
For each Rails application project, RubyMine provides default Rails run/debug configurations for the production and development environments.

What is the difference between a plugin and a gem?
A. A gem is just ruby code. It is installed on a machine and it’s available for all ruby applications running on that machine. Rails, rake, json, rspec — are all examples of gems.
Plugin is also ruby code but it is installed in the application folder and only available for that specific application.
Sitemap-generator, etc.
In general, since Rails works well with gems you will find that you would be mostly integrating with gem files and not plugins in general. Most developers release their libraries as gems.

What is restful in rails

A.Stands for REpresentational State Transfer


What is passanger
A. Easy and robust deployment of ruby on rails app on appache and ngix webservers
passenger is an intermediate to run the ruby language in linux server

 What is request.xhr?
A: A request.xhr tells the controller that the new Ajax request has come, It always return TRUE or FALSE

What is the Difference between Static and Dynamic Scaffolding?
A: The Syntax of Static Scaffold is like this:
ruby script/generate scaffold User Comment
Where Comment is the model and User is your controller, So all n all static scaffold takes 2 parameter i.e your controller name and model name, whereas in dynamic scaffolding you have to define controller and model one by one.

What is Session and Cookies?
A: Session: are used to store user information on the server side.
cookies: are used to store information on the browser side or we can say client side
Session : say session[:user] = “srikant” it remains when the browser is not closed

What is the difference between form_for and form_tag

A. form_tag and form_for both are used to submit the form and it’s elements.
The main difference between these two is the way of managing objects related to that particular model is different.
We should use “form_for” tag for a specific model
It performs the “standard http post” which is having fields related to active record (model) objects

It creates a form as a normal form. form_tag also performs the “standard http post” without any model backed and has normal fields. This is mainly used when specific data need to be submitted via form.
It just creates a form tag and it is best used for non-model forms.


<% form_tag ‘/articles’ do -%>
<%= text_field_tag “article”, “firstname” %>
<% end -%>

Difference between ruby 1.8.7 and 1.9.2

A.Ruby 1.9 – Major Features

gems is (mostly) built-in now
if statements do not introduce scope in Ruby.

-{“a”,”b”} No Longer Supported
-Array.to_s Now Contains Punctuation
-Colon No Longer Valid In When Statements

What are the engines in mysql
Ans: In previous versions of MySQL, MyISAM was the default storage engine. In our experience, most users never changed the default settings. With MySQL 5.5, InnoDB becomes the default storage engine.

What is the difference between include and extend
A.include makes the module’s methods available to the instance of a class, while
extend makes these methods available to the class itself.
When you use include, the module’s methods are added to the instances of the class. The log method is:

Not available at the class level
Available at the instance level
Not available at the class level again

When you use extend, the module’s methods are added to the class itself. The log method is:

Available at the class level.
Not available at the instance level.
Available at the class level.

What is the difference between lambada and proc

A.proc and Lambda are used to create code blocks. After creating them, we can pass them around our code, just like variables.

How to call method dynamically

A.[“foo”, “bar”].each do |method|

How to create a method dynamically

A.class Message
[:hello, :goodbye].each do |method_name|
define_method method_name do |arg|
“#{method_name} #{arg}”

Message.instance_methods false #=> [:hello, :goodbye] ’emre’ #=> “hello emre” ’emre’ #=> “goodbye emre”

How to use Nested routes in ROR

The easiest way to create a nested route, is to use the :has_many keyword like that:

# /config/routes.rb
map.resources :projects, :has_many => :tasks

# and the correspondent task resource
map.resources :tasks

Adding the second routes, that defines a RESTful route to :tasks, depends if you would like to allow an access to the Task resource, without the project context, this is not a must.

What things we can define in the model?
A: There are lot of things you can define in models few are:
1. Validations (like validates_presence_of, numeracility_of, format_of etc.)
2. Relationships(like has_one, has_many, HABTM etc.)
3. Callbacks(like before_save, after_save, before_create etc.)
4. Suppose you installed a plugin say validation_group, So you can also define validation_group settings in your model
5. ROR Queries in Sql

How many Types of Relationships does a Model has?
A: * (1) has_one
* (2) belongs_to
* (3) has_many
* (4) has_many :through

What is asset pipeline
A.asset pipeline which enables proper organization of CSS and JavaScript

What is observer in rails

A:Observer classes respond to life cycle callbacks to implement trigger-like behavior outside the original class.

Rails observers are sweet, You can observe multiple models within a single observer

First, you need to generate your observer:

command – rails g observer Auditor

-observer classes are usually stored in app/models with the naming convention of app/models/audit_observer.rb.

In order to activate an observer, list it in the config.active_record.observers configuration setting in your config/application.rb file.

config.active_record.observers = :comment_observer, :signup_observer
Observers will not be invoked unless you define these in your application configuration.
What is rails sweeper
One sweeper can observe many Models, and any controller can have multiple sweepers.

Difference between -%> and %> in rails
A:The extra dash makes ERB not output the newline after the closing tag. There’s no difference in your example, but if you have something like this:

<% if true -%>
<% end -%>

It’ll produce:


and not this:


Difference between render and redirect?
Redirect is a method that is used to issue the error message in case the page is not found or it issues a 302 to the browser. Whereas, render is a method used to create the content.

-Redirect is used to tell the browser to issue a new request. Whereas, render only works in case the controller is being set up properly with the variables that needs to be rendered.

-Redirect is used when the user needs to redirect its response to some other page or URL. Whereas, render method renders a page and generate a code of 200.

-Redirect is used as:
redirect_to: controller => ‘users’, :action => ‘new’

-Render is used as:
render: partial
render: new -> this will call the template named as new.rhtml without the need of redirecting it to the new action.

What is the use of rake db:reset

A.db:create——- creates the database for the current env
db:create:all ———creates the databases for all envs
db:drop ———-drops the database for the current env
db:drop:all ———-drops the databases for all envs
db:migrate ———-runs migrations for the current env that have not run yet
db:migrate:up ——–runs one specific migration
db:migrate:down ——-rolls back one specific migration
db:migrate:status —–shows current migration status
db:migrate:rollback —rolls back the last migration
db:forward ————advances the current schema version to the next one
db:seed (only) ———runs the db/seed.rb file
db:schema:load ————loads the schema into the current env’s database
db:schema:dump ———dumps the current env’s schema (and seems to create the db aswell)

db:setup ————-runs db:schema:load, db:seed

db:reset ———-runs db:drop db:setup
db:migrate:redo ———runs (db:migrate:down db:migrate:up) or (db:migrate:rollback db:migrate:migrate) depending on the specified migration
db:migrate:reset ——runs db:drop db:create db:migrate

What is eagerloading
A.-One way to improve performance is to reduce the number of database queries through eager loading.
-You can know where we need eager loading through “Bullet’ Gem

How to use sql db or mysql db. without defining it in the database.yml

What are helpers and how to use helpers in ROR?
A. Helpers (“view helpers”) are modules that provide methods which are automatically usable in your view. They provide shortcuts to commonly used display code and a way for you to keep the programming out of your views. The purpose of a helper is to simplify the view. It’s best if the view file (RHTML/RXML) is short and sweet, so you can see the structure of the output.

What is Active Record?
A. Active Record are like Object Relational Mapping(ORM), where classes are mapped to table and objects are mapped to colums in the table

Ruby Supports Single Inheritence/Multiple Inheritence or Both?
A. Ruby Supports only Single Inheritnece

How many types of callbacks available in ROR?
A. * (-) save
* (-) valid
* (1) before_validation
* (2) before_validation_on_create
* (-) validate
* (-) validate_on_create
* (3) after_validation
* (4) after_validation_on_create
* (5) before_save
* (6) before_create
* (-) create
* (7) after_create
* (8) after_save

How to use two database into a Single Application?

A., According to this link : ActiveRecord models are allowed one connection to a database at a time, per class. Ruby on Rails sets up the default connection based on your database.yml configuration to automatically select development, test or production.
But, what if you want to access two or more databases – have 2+ connections open – at the same time. ActiveRecord requires that you subclass ActiveRecord::Base.
That prevents you doing migrations from one database to another. It prevents you using one set of model classes on two or more databases with the same schema.
Magic Multi-Connections allows you to write your models once, and use them for multiple Rails databases at the same time. How? Using magical namespacing.

To do this :
[A] sudo gem install magic_multi_connections
[B] require ‘magic_multi_connections’
Add the following to the bottom of your environment.rb file
You can also find examples on this link :

“Updated Set of Questions for Rails 3”

What is the difference between the Rails version 2 and 3?
A. * (1) Introduction of bundler (New way to manage your gem dependencies)
* (2) Gemfile and Gemfile.lock (Where all your gem dependencies lies, instead of environment.rb)
* (3) A new .rb file in config/ folder, named as application.rb (Which has everything that previously environment.rb had)
* (4) Change in SQL Structure: Model.where(:activated => true)
* (5) All the mailer script will now be in app/mailers folder, earlier we kept inside app/models.
* (6) Rails3-UJS support. for links and forms to work as AJAX, instead of writing complex lines of code, we write :remote => true
* (7) HTML 5 support.
* (8) Changes in the model based validation syntax: validates :name, :presence => true
* (9) Ability to install windows/ruby/jruby/development/production specific gems to Gemfile.
group :production do
gem ‘will_paginate’

What is bundler?
A: Bundler is a new concept introduced in Rails3, which helps to you manage your gems for the application. After specifying gems in your Gemfile, you need to do a bundle install. If the gem is available in the system, bundle will use that else it will pick up from the

What is the Newest approach for find(:all) in Rails 3?
A: Model.where(:activated => true)

Ruby Interview Questions :

What are the variable in ruby

A.1 Local Variables – foobar
2 Instance Variables – @foobar
3 Class Variables – @@foobar
4 Global Variables – $foobar
Name Begins With Variable Scope
$ A global variable
@ An instance variable
[a-z] or _ A local variable
[A-Z] A constant
@@ A class variable

Difference between “and” and && in Ruby?
A.and is the same as && but with lower precedence.

Difference between method overloading and method overwriting

A.def: In Method Overloading, Methods of the same class shares the same name but each method must have different number of parameters or parameters having different types and order.

Method Overloading means more than one method shares the same name in the class but having different signature.
In Method Overloading, methods must have different signature.
Method Overloading does not require more than one class for overloading.

Def:In Method Overriding, sub class have the same method with same name and exactly the same number and type of parameters and same return type as a super class.

Method Overriding means method of base class is re-defined in the derived class having same signature.
In Method Overriding, methods must have same signature.
Method Overriding requires at least two classes for overriding.

What is the Notation used for denoting class variables in Ruby?
A:We can know a variable as “Class variable’s” if its preceeded by @@ symbols.

What is the use of Destructive Method?
A:Distructive methods are used to change the object value permanently by itself using bang (!) operator.
‘sort’ returns a new array and leaves the original unchanged.
‘sort!’ returns the same array with the modification.
The ‘!’ indicates it’s a destructive method. It will overwrite the current array with the new result and returns it.

What is the use of load and require in Ruby?
A:The require() method is quite similar to load(), but it’s meant for a different purpose.
You use load() to execute code, and you use require() to import libraries.

What is the use of Global Variable in Ruby?
A:Syntatically, a global variable is a variable whose name begins with $
Global variables in Ruby are accessible from anywhere in the Ruby program, regardless of where they are declared.
$welcome = “Welcome to Ruby Essentials”

How does nil and false differ?
A:nil cannot be a value, where as a false can be a value
A method returns true or false in case of a predicate, other wise nil is returned.
false is a boolean data type, where as nil is not.
nil is an object for NilClass, where as false is an object of for FalseClass

What is the diffence betweet symbol and string
A. Symbols have two nice properties compared to strings which can save you memory and CPU time
The difference remains in the object_id, memory and process time for both of them when used together at one time
Strings are considered as mutable objects. Whereas, symbols, belongs to the category of immutable
Strings objects are mutable so that it takes only the assignments to change the object information. Whereas, information of, immutable objects gets overwritten

How to use super key word

A.Ruby uses the super keyword to call the superclass implementation of the current method.
Within the body of a method, calls to super acts just like a call to that original method.
The search for a method body starts in the superclass of the object that was found to contain the original method.
def url=(addr)
super (addr.blank? || addr.starts_with?(‘http’)) ? addr : http://#{addr}

How is visibility of methods change in Ruby?

What is a Class Instance Variable

What are the rules and conventions to be followed in Ruby for naming a method?

How is class method defined in Ruby?

What are the Operators available in Ruby?

What are the looping structure available in Ruby?

What is the scope of local variable?

What are the OOP supported by Ruby?

If Ruby over PHP, Why?

Garbage collection in Ruby?

Environment Variables in Ruby?

What are Float, Dig and Max?
Ans.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.
Max is used whenever there is a huge need of Float.
Dig is used whenever you want to represent a float in decimal digits.
What is Ruby Code blocks?

What kind of conditions ruby support?

Difference between puts and print
Ans.puts adds a newline to the end of the output. print does not.

Is there any technology apart from agile which we can use?

What are the servers supported by ruby on rails application?

Passenger running on Apache. Easy to set up, low memory usage, and well supported.
nginx with puma(it is a multi-threaded high performance webserver written in Ruby).

What is Meta-programming? How you are using it inside your rails application?

What is has_many?
Ans. It is a way of defining relationships among models. Correct, and Do you guys really know has_many is also an example of Meta-programming? Wondering, How?

What is TDD and BDD?
A: Test-Driven-Development and Behavior-Driven-Development

What is rspec, cucumber and Watir? And what it has to do with TDD and BDD?

What is the difference between ‘&&’ and ‘||’ operators?

A. “&&” has higher precedence than “||” like in most other mainstream languages; but “or” and “and” in ruby have the same(!) precedence level!
so if you write
(func1 || func2 && func3), it’s (func1 || (func2 && func3))
(func1 or func2 and func3) is interpreted as ((func1 or func2) and func3)
because of shorcircuiting, if func1 is true, both func2 and func3 won’t be called at all in the first example
but in the second example func3 WILL be called!
this difference is subtile enough that I really do not recommend newbies to use “and” and “or” in ruby at all.

What is the Purpose of “!” and “?” at the end of method names?
A. It’s “just sugarcoating” for readability, but they do have common meanings:
Methods ending in ! perform some permanent or potentially dangerous change; for example:
Enumerable#sort returns a sorted version of the object while Enumerable#sort! sorts it in place.
In Rails, ActiveRecord::Base#save returns false if saving failed, while ActiveRecord::Base#save! raises an exception.
Kernel::exit causes a script to exit, while Kernel::exit! does so immediately, bypassing any exit handlers.
Methods ending in ? return a boolean, which makes the code flow even more intuitively like a sentence — if reads like “if the number is zero”, but if just looks weird.
In your example, name.reverse evaluates to a reversed string, but only after the name.reverse! line does the name variable actually contain the reversed name. name.is_binary_data? looks like “is name binary data?”.

Just remember it in simple
In Ruby the ? means that the method is going to return a boolean and the ! modifies the object it was called on. They are there to improve readability when looking at the code.

How can you list all routes for an application?
A) By writing rake routes in the terminal we can list out all routes in an application.

What is rake?
A) rake is command line utility of rails. “Rake is Ruby Make, a standalone Ruby utility that replaces the Unix utility ‘make’, and uses a ‘Rakefile’ and .rake files to build up a list of tasks. In Rails, Rake is used for common administration tasks, especially sophisticated ones that build off of each other.”

Putting in simple word : “rake will execute different tasks(basically a set of ruby code) specified in any file with .rake extension from comandline.”

What are the differences between MongoDB and Redis?

A) Redis is a key value store while mongoDB is a document store.
  1.Data model
Document oriented, JSON-like. Each document has unique key within a collection. Documents are heterogenous.
Key-value, values are:

  • Lists of strings
  • Sets of strings (collections of non-repeating unsorted elements)
  • Sorted sets of strings (collections of non-repeating elements ordered by a floating-point number called score)
  • Hashes where keys are strings and values are either strings or integers After Wikipedia.

Disk, memory-mapped files, index should fit in RAM.
Typically in-memory.
By key, by any value in document (indexing possible), Map/Reduce.
By key.

What are the new features of Rails4?
1. Ruby Versions
2. ‘Gemfile’
3. ‘Threadsafe’ by Default
4. No More vendor/plugins
5. New Testing Directories
6. Strong Parameters
7. Renamed Callback
10. Queuing system
13. Cache Digests (Russian Doll Caching)
14. Turbolinks

More Questions and Answers of this will be published very soon 🙂 

20 thoughts on “Ruby on Rails Interview Questions and Answers

  1. Pingback: RoR | thoughs
  2. We are a group of volunteers and starting a new scheme
    in our community. Your web site offered us with helpful info
    to work on. You have performed an impressive activity and our entire neighborhood will probably be thankful to

  3. Hello,
    I found the questions to be very helpful. But the first answer says “view interacts with the model” as far as I know view cannot interact with anyone directly. So view displays things and hence controller handels all the interactions with the models. I am confused please explain

  4. Awesome article, but you might want to edit the part that says “your view interacts with mode” under the MVC part. The view doesn’t know anything about the model, it’s the controller that interacts with the model then the controller will send back to information to the views.

  5. Whatever knowledge we share on internet we try others to learn from it. I am not sure how far your learning went but you’ve actually showcased it by copying the content from my website and used it for your own good (without even changing the actual text for the questions).
    By default the content we write, the article we publish is copyright and we ensure that no one use it illegally.
    You can seek permission before putting the content on your website or can put up a link (as a reference).
    Why haven’t you copied any post/content from Railscasts? Try to stick to basic blogging principles. If you consider yourself as a good programmer, try to come up with your own articles.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s