Real Time 50 top Ruby on Rails Interview Questions and answers for freshers and experienced job interview questions pdf

Ruby on Rails Interview Questions and Answers List

1. In which Programming language was Ruby written?
Ruby was written in C language and Ruby on Rails written in Ruby.

2. Why Ruby on Rails?
There are lots of advantage of using Ruby on Rails.

(i) DRY Principal( Don’t Repeat Yourself): It is a principle of software development aimed at reducing repetition of code. “Every piece of code must have a single, unambiguous representation within a system”
(ii) Convention over Configuration: Most web development framework for .NET or Java force you to write pages of configuration code. If you follow suggested naming conventions, Rails doesn’t need much configuration.
(iii) Gems and Plugins: RubyGems is a package manager for the Ruby programming language that provides a standard format for distributing ruby programs and library.
Plugins: A Rails plugin is either an extension or a modification of the core framework. It provides a way for developers to share bleeding-edge ideas without hurting the stable code base. We need to decide if our plugin will be potentially shared across different Rails applications.
(iv) Scaffolding: Scaffolding is a meta-programming method of building database-backend software application. It is a technique supported by MVC frameworks, in which programmer may write a specification, that describes how the application database may be used. There are two type of scaffolding:
-static: Static scaffolding takes 2 parameter i.e your controller name and model name.
-dynamic: In dynamic scaffolding you have to define controller and model one by one.
(v) Rack Support: Rake is a software task management tool. It allows you to specify tasks and describe dependencies as well as to group tasks in a namespace.
(vi) Metaprogramming: Metaprogramming techniques use programs to write programs.
(vii) Bundler: Bundler is a new concept introduced in Rails 3, which helps you to manage your gems for application. After specifying gem file, you need to do a bundle install.
(viii) Rest Support.
(ix) Action Mailer

3. What is MVC? and How it Works?
MVC basically indicates Model-View-Controller. And MVC used by many languages like PHP, Perl, Python etc. Generally MVC works like this:
Request first comes to the controller, controller finds and appropriate view and interacts with model, model interacts with your database and send the response to controller then controller based on the response give the output parameter to view.

Ruby on Rails
Ruby on Rails Interview Questions

4. How many types of relationships does a Model has?
(i) has_one
(ii) belongs_to
(iii) has_many
(iv) has_many :through

5. What is Ruby Gems?
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.

6. What is Session and Cookies?
Session is used to store user information on the server side where as Cookies are used to store the information in the client side.

7. What is a symbol and how it differs from variable?
Symbol in Ruby is basically the same thing as symbol in the real world. It is used to represent or name something. Symbols are very commonly used to represent some kind of state, for example
order.status = :canceled
order.status = :confirmed
Variables and Symbols are different things. A variable points to different kind of datIn Ruby, a symbol is more like a string than a variable.
In Ruby, a string is mutable, where as a symbol is immutable. That means that only one copy of a symbol needs to be created. symbols are often used as the equivalent to enums in Ruby, as well as keys to a dictionary (hash).

8. What is the difference between Symbol and String in Ruby?
-The symbol in Ruby on rails act the same way as the string but the difference is in their behaviors that are opposite to each other.
-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.
-String objects are written like
p: “string object jack”.object_id #=>2250 or
p: “string object jack”.to_sym.object_id #=> 2260, and
p: “string object jack”. to_s_object_id #=> 2270
-Symbols are used to show the values for the actions like equality or non-equality to test the symbols faster then the string values.

9. What is the basic difference between GET and POST method?
GET is basically for just getting (retrieving) the data, whereas POST may used to do multiple things, like storing or updating data, or ordering a product, or sending E-mail etc.

10. What id the difference between Static and Dynamic Scaffolding?
The Syntax of Static Scaffold is like this: ruby script/generate scaffold Home New
Where New is the model and Home is your controller, In this way 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.

11. What is ORM Rails ?
ORM stands 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.

12. Does Ruby supports Multiple Inheritance?
No, Ruby supports only single Inheritance.

13.Is there any alternative of Multiple inheritance in Ruby? Please Explain.
Yes, Ruby offers a very neat alternative concept called mixin. Modules can be imported inside other class using mixin. They are then mixed-in with the class in which they are imported.

14. What is Bundler?
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 rubygems.org.
Here is a best link i got http://bundler.io/ to know more bundler more.

15. What are class variables? How do you define them?
Class variables are created using the @@ prefix to denote the variable as class level. It works just like any other variable, however in the case of inheritance it works more like a static variable that is accessed across all variable instances.

16. Does Ruby support constructors? How are they declared?
Constructors are supported in Ruby. They are declared as the method initialize, shown below. The initialize method gets called automatically when Class.new is called.

17. What is the purpose of Yield in Ruby?
Ruby provides a yield statement that eases the creation of iterators.
The first thing I noticed was that its behavior is different from the C# yield statement (which I knew from before).
Ruby’s yield statement gives control to a user specified block from the method’s body. A classic example is the Fibonacci Sequence:

class NumericSequences
def fibo(limit)
i = 1
yield 1
yield 1
a = 1
b = 1
while (i < limit) t = a a = a + b b = t yield a i = i+1 end end … end The fibo method can be used by specifying a block that will be executed each time the control reaches a yield statement. For example: irb(main):001:0> g = NumericSequences::new
=> #
irb(main):002:0> g.fibo(10) {|x| print “Fibonacci number: #{x}\n”}
Fibonacci number: 1
Fibonacci number: 1
Fibonacci number: 2
Fibonacci number: 3
Fibonacci number: 5
Fibonacci number: 8
Fibonacci number: 13
Fibonacci number: 21
Fibonacci number: 34
Fibonacci number: 55
Fibonacci number: 89

18. What is the difference between Render & 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.

19. How do you define Class Variable, Instance Variable and Global Variable in Ruby?
Ruby Class Variables
Class variables begin with @@ and must be initialized before they can be used in method definitions.
Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.
Overriding class variables produce warnings with the -w option.
Here is an example showing usage of class variable:
class Customer
def initialize(id, name, addr)
def display_details()
puts “Customer id #@cust_id”
puts “Customer name #@cust_name”
puts “Customer address #@cust_addr”
def total_no_of_customers()
@@no_of_customers += 1
puts “Total number of customers: #@@no_of_customers”

# Create Objects
cust1=Customer.new(“1”, “John”, “Wisdom Apartments, Ludhiya”)
cust2=Customer.new(“2”, “Poul”, “New Empire road, Khandala”)

# Call Methods
Here @@no_of_customers is a class variable. This will produce following result:
Total number of customers: 1
Total number of customers: 2
Ruby Instance Variables
Instance variables begin with @. Uninitialized instance variables have the value nil and produce warnings with the -w option.
Here is an example showing usage of Instance Variables.

class Customer
def initialize(id, name, addr)
def display_details()
puts “Customer id #@cust_id”
puts “Customer name #@cust_name”
puts “Customer address #@cust_addr”

# Create Objects
cust1=Customer.new(“1”, “John”, “Wisdom Apartments, Ludhiya”)
cust2=Customer.new(“2”, “Poul”, “New Empire road, Khandala”)

# Call Methods
Here @cust_id, @cust_name and @cust_addr are instance variables. This will produce following result:
Customer id 1
Customer name John
Customer address Wisdom Apartments, Ludhiya
Customer id 2
Customer name Poul
Customer address New Empire road, Khandala
Ruby Global Variables
Global variables begin with $. Uninitialized global variables have the value nil and produce warnings with the -w option.
Assignment to global variables alters global status. It is not recommended to use global variables. They make programs cryptic.
Here is an example showing usage of global variable.

$global_variable = 10
class Class1
def print_global
puts “Global variable in Class1 is #$global_variable”
class Class2
def print_global
puts “Global variable in Class2 is #$global_variable”

class1obj = Class1.new
class2obj = Class2.new
Here $global_variable is a global variable. This will produce following result:
NOTE: In Ruby you CAN access value of any variable or constant by putting a hash (#) character just before that variable or constant.
Global variable in Class1 is 10
Global variable in Class2 is 10

20. What is Gemfile and Gemfile.lock?
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.

21. What is the difference between puts and print ?
puts appends a new line and outputs each argument to a new line but print doesn’t append anything and seems to separate arguments by a space.

22. What is has_many ?
A has_many association indicates a one-to-many connection with another model. You’ll often find this association on the “other side” of a belongs_to association. This association indicates that each instance of the model has zero or more instances of another model. For example, in an application containing customers and orders, the customer model could be declared like this:
class Customer < ActiveRecord::Base
has_many :orders
The corresponding migration might look like this:
class CreateCustomers < ActiveRecord::Migration def change create_table :customers do |t| t.string :name t.timestamps end create_table :orders do |t| t.belongs_to :customer t.datetime :order_date t.timestamps end end end 23. How to use sql db or mysql db without defining it in the database.yml? You can use ActiveRecord anywhere require “rubygems” require “active_record” ActiveRecord::Base.establish_connection({ :adapter=> ‘postgresql’, :user=>’foo’, :password=> ‘abc’, :database=>’whatever’})

24. How you run your Rails application without creating databases?
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

25. What are the servers supported by ruby on rails?
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.

26. Can we use two databases into a single application?
Yes, Definitely. magic multi-connections allows you to write your model once, and use them for the multiple rails databases at the same time.
sudo gem install magic_multi_connection. After installing this gem, just add this line at bottom of your environment.rb require “magic_multi_connection”

27. What is scope?
Scopes are nothing more than SQL scope fragments. By using these fragments one can cut down on having to write long queries each time you access content.

28. Can you give an example of a class that should be inside the lib folder?
Modules are often placed in the lib folder.

29. Where should you put code that is supposed to run when your application launches?
In the rare event that your application needs to run some code before Rails itself is loaded, put it above the call to require ‘rails/all’ in config/application.rb.

30. What deployment tool do you use?
Capistrano is a popular deployment tool, it allows developers to push code from their desktop to the servers. you can also use chef as a deployment tool for your project.

31. What is a filter? When it is called?
Filters are methods that are called either before/after a controller action is called.

32. What is the difference between a plugin and a gem?
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.

33. How many types of callbacks available in ROR?
Different types of callbacks available in ROR like:
(1) before_validation
(2) before_validation_on_create
(3) validate_on_create
(4) after_validation
(5) after_validation_on_create
(6) before_save
(7) before_create
(8) after_create
(9) after_save

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

35. How to serialize data with YAML?
YAML is a straight forward machine parsable data serialization format, designed for human readability and interaction with scripting language such as Perl and Python.
YAML is optimized for data serialization, formatted dumping, configuration files, log files, internet messaging and filtering.

36. What are Filters?
Filters are methods that run “before”, “after” or “around” a controller action. Filters are inherited, so if you set a filter on Application Controller, it will be run on every controller in your application.

37. Explain the Naming Convention in Rails.
Variables: Variables are named where all letters are lowercase and words are separated by underscores. E.g: total, order_amount.
Class and Module: Classes and modules uses MixedCase and have no underscores, each word starts with a uppercase letter. Eg: InvoiceItem
Database Table: Table name have all lowercase letters and underscores between words, also all table names to be plural. Eg: invoice_items, orders etc
Model: The model is named using the class naming convention of unbroken MixedCase and always the singular of the table name.
For eg: table name is might be orders, the model name would be Order. Rails will then look for the class definition in a file called order.rb in /app/model directory. If the model class name has multiple capitalized words, the table name is assumed to have underscores between these words.
Controller: controller class names are pluralized, such that OrdersController would be the controller class for the orders table. Rails will then look for the class definition in a file called orders_controlles.rb in the /app/controller directory.

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

39. What is a Range in Ruby?
The first and perhaps most natural use of ranges is to express a sequence. Sequences have a start point, an end point, and a way to produce successive values in the sequence. In Ruby, these sequences are created using the “..” and “…” range operators. The two dot form creates an inclusive range, and the three-dot form creates a range that excludes the specified high value. In Ruby ranges are not represented internally as lists: the sequence 1..100000 is held as a Range object containing references to two Fixnum objects. Refer program p021ranges.rb. If you need to, you can convert a range to a list using the to_a method.
(1..10).to_a -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Ranges implement methods that let you iterate over them and test their contents in a variety of ways.
# p021ranges.rb
Sequences have a start point, an end point, and a way to
produce successive values in the sequence
In Ruby, sequences are created using the “..” and “…”
range operators.
The two dot form creates an inclusive range.
The three-dot form creates a range that excludes the specified
high value
The sequence 1..100000 is held as a Range object
digits = -1..9
puts digits.include?(5) # true
puts digits.min # -1
puts digits.max # 9
puts digits.reject {|i| i < 5 } # [5, 6, 7, 8, 9] Another use of the versatile range is as an interval test: seeing if some value falls within the interval represented by the range. We do this using ===, the case equality operator. (1..10) === 5 -> true
(1..10) === 15 -> false
(1..10) === 3.14159 -> true
(‘a’..’j’) === ‘c’ -> true
(‘a’..’j’) === ‘z’ -> false

40. How can you implement method overloading?
You want to create two different versions of a method with the same name: two methods that differ in the arguments they take. However, a Ruby class can have only one method with a given name (if you define a method with the same name twice, the latter method definition prevails as seen in example p038or.rb in topic Ruby Overriding Methods). Within that single method, though, you can put logic that branches depending on how many and what kinds of objects were passed in as arguments.
Here’s a Rectangle class that represents a rectangular shape on a grid. You can instantiate a Rectangle by one of two ways: by passing in the coordinates of its top-left and bottom-right corners, or by passing in its top-left corner along with its length and width. There’s only one initialize method, but you can act as though there were two.
# The Rectangle constructor accepts arguments in either
# of the following forms:
# Rectangle.new([x_top, y_left], length, width)
# Rectangle.new([x_top, y_left], [x_bottom, y_right])
class Rectangle
def initialize(*args)
if args.size < 2 || args.size > 3
# modify this to raise exception, later
puts ‘This method takes either 2 or 3 arguments’
if args.size == 2
puts ‘Two arguments’
puts ‘Three arguments’
Rectangle.new([10, 23], 4, 10)
Rectangle.new([10, 23], [14, 13])
The above program p037rectangle.rb is incomplete from the Rectangle class viewpoint, but is enough to demonstrate how method overloading can be achieved. Also remember that the initialize method takes in a variable number of arguments.

41. What is the difference between ‘&&’ and ‘||’ operators?
“&&” 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.

42. Why Explanation marks used in Ruby?
In general, methods that end in ! indicate that the method will modify the object it’s called on. Ruby calls these “dangerous methods” because they change state that someone else might have a reference to. Here’s a simple example for strings:
foo = “A STRING” # a string called foo
foo.downcase! # modifies foo itself
puts foo # prints modified foo
This will output:
a string
In the standard libraries, there are a lot of places you’ll see pairs of similarly named methods, one with the ! and one without. The ones without are called “safe methods”, and they return a copy of the orignal with changes applied to the copy, with the callee unchanged. Here’s the same example without the !:
foo = “A STRING” # a string called foo
bar = foo.downcase # doesn’t modify foo; returns a modified string
puts foo # prints unchanged foo
puts bar # prints newly created bar
This outputs:
a string
Keep in mind this is just a convention, but a lot of ruby classes follow it. It also helps you keep track of what’s getting modified in your code.

43. What is the Purpose of “!” and “?” at the end of method names?
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 number.zero? reads like “if the number is zero”, but if number.zero 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?”.
🙂 Confused ?
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.

44. What is Mixin ?
Ruby does not suppoprt mutiple inheritance directly but Ruby Modules have another, wonderful use. At a stroke, they pretty much eliminate the need for multiple inheritance, providing a facility called a mixin. Mixins give you a wonderfully controlled way of adding functionality to classes. However, their true power comes out when the code in the mixin starts to interact with code in the class that uses it.
let me give a small example
module A
def a1
def a2
module B
def b1
def b2

class Sample
include A
include B
def s1

Module A consists of the methods a1 and a2. Module B consists of the methods b1 and b2. The class Sample includes both modules A and B. The class Sample can access all four methods, namely, a1, a2, b1, and b2. Therefore, you can see that the class Sample inherits from both the modules. Thus you can say the class Sample shows multiple inheritance or a mixin.
(Source: http://www.tutorialspoint.com/ruby/ruby_modules.htm)

45. What is purpose of RJs in Rails ?
A) RJS is a template (similar to an html.erb file) that generates JavaScript which is executed in an eval block by the browser in response to an AJAX request. It is sometimes used (incorrectly?) to describe the JavaScript, Prototype, and Scriptaculous Helpers provided by Rails. This may Help you more.

46. What is eager loading, lazy loading and over-eager loading?
Generally three levels are there:
Eager loading: you do everything when asked. Classic example is when you multiply two matrices. You do all the calculations. That’s eager loading;
Lazy loading: you only do a calculation when required. In the previous example, you don’t do any calculations until you access an element of the result matrix; and Over-eager loading: this is where you try and anticipate what the user will ask for and preload it.
For Example:
Imagine a page with rollover images like for menu items or navigation. There are three ways the image loading could work on this page:
Load every single image required before you render the page (eager);
Load only the displayed images on page load and load the others if/when they are required (lazy); and
Load only the displayed images on page load. After the page has loaded preload the other images in the background in case you need them (over-eager).

47. How can you define a constant?
Constants defined within a class or module can be accessed from within that class or module, and those defined outside a class or module can be accessed globally. Constants begin with an uppercase letter. Constants may not be defined within methods. Referencing an uninitialized constant produces an error. Making an assignment to a constant that is already initialized produces a warning.
class Example
VAR1 = 100
VAR2 = 200
def show
puts “Value of first Constant is #{VAR1}”
puts “Value of second Constant is #{VAR2}”

# Create Objects

Here VAR1 and VAR2 are constant. This will produce following result:
Value of first Constant is 100
Value of second Constant is 200

48. How can you call the base class method from inside of its overriden method?
The A::foo will call B::bar if you have an instance of B. It does not matter if the instance is referenced through a pointer or a reference to a base class: regardless of this, B’s version is called; this is what makes polymorphic calls possible. The behavior is not compiler-specific: virtual functions behave this way according to the standard.

49. What is an observer?
Observer serves as a connection point between models and some other subsystem whose functionality is used by some of other classes, such as email notification. It is loose coupling in contract with model callback.

50. How can you implement rails observer for multiple models?
Implementing Rails Observer are simple. You can observe multiple models within a single observer.
First you need to generate your observer.
rails g observer Auditor
Then, in your fresh auditor_observer.rb file define the models you wish to observe and then add theafter_create callback.
class AuditorObserver < ActiveRecord::Observer
observe :model_foo, :model_bar, :model_baz
def after_create(record)
#do something with `record`
And It should work.