Tuesday 30 July 2013

Some Helpful Development Environment for ROR

Hi All,

I got some ROR Development Environment tools from Google. This may help you. Checkout the below links

1. Foreman - http://michaelvanrooijen.com/articles/2011/06/08-managing-and-monitoring-your-ruby-application-with-foreman-and-upstart/

2. Unicorn - https://github.com/blog/517-unicorn

3. Bluepill - https://github.com/arya/bluepill

4. Upstart - http://upstart.ubuntu.com/

Enjoy  :)

Sunday 28 July 2013

Ruby on Rails Interview Questions & Answers

Hello Friends...
Interviews are being very tough these days as a vast competition in the market. New technologies releasing each moment to make it more competitive. And as you know Ruby on Rails is a most demanded Domain these days. Here I have collected some Interview Questions and their Answers from different sources. I have prepared this keeping in view all the ROR Lovers. Hope this will be helpful for all Junior level Interview attending candidates.

First of all let let me give a small introduction about Ruby on Rails.
 Ruby on Rails is a dynamic & reflective object oriented programming language that includes syntex inspired by Perl and Smalltalk like features. Ruby was first designed & developed by Yukihiro "Matz" Matsumoto in Japan in the mid 1990s. It was written in C as a single pass interpreted language. The language specification for Ruby were developed by the Open Standards Promotion Center of the Information Technology Promotion Agency (A Japanese Government Agency) for submission to the Japanese Industrial Standards Committee and then to the International Organization for Standardization.

Question & Answer
1. In which Programming language was Ruby written?
A. Ruby was written in C language and Ruby on Rails written in Ruby.

2. Why Ruby on Rails?
A. 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?
A. 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.
4. How many types of relationships does a Model has?
A.  (i) has_one
      (ii) belongs_to
      (iii) has_many
      (iv) has_many :through

5. 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.
6.  What is Session and Cookies?
A. 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?
A. 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 data. In 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?
A. -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?
A. 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?
A. 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 ?
A. 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?
A. No, Ruby supports only single Inheritance.
13.Is there any alternative of Multiple inheritance in Ruby? Please Explain.
A. 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?
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 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?
A. 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?
A. 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?
A.  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
=> #<NumericSequences:0xb7cd703c>
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?
A. -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?
A. 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:
#!/usr/bin/ruby

class Customer
   @@no_of_customers=0
   def initialize(id, name, addr)
      @cust_id=id
      @cust_name=name
      @cust_addr=addr
   end
   def display_details()
      puts "Customer id #@cust_id"
      puts "Customer name #@cust_name"
      puts "Customer address #@cust_addr"
    end
    def total_no_of_customers()
       @@no_of_customers += 1
       puts "Total number of customers: #@@no_of_customers"
    end
end

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

# Call Methods
cust1.total_no_of_customers()
cust2.total_no_of_customers()
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.
#!/usr/bin/ruby

class Customer
   def initialize(id, name, addr)
      @cust_id=id
      @cust_name=name
      @cust_addr=addr
   end
   def display_details()
      puts "Customer id #@cust_id"
      puts "Customer name #@cust_name"
      puts "Customer address #@cust_addr"
    end
end

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

# Call Methods
cust1.display_details()
cust2.display_details()
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.
#!/usr/bin/ruby

$global_variable = 10
class Class1
  def print_global
     puts "Global variable in Class1 is #$global_variable"
  end
end
class Class2
  def print_global
     puts "Global variable in Class2 is #$global_variable"
  end
end

class1obj = Class1.new
class1obj.print_global
class2obj = Class2.new
class2obj.print_global
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
 (Source: http://www.tutorialspoint.com/ruby/ruby_variables.htm)
20. 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.

21. What is the difference between puts and print ?
A. 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. 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
end
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
(Source: http://guides.rubyonrails.org/association_basics.html)

23.  How to use sql db or mysql db without defining it in the database.yml?
A. 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?
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
25. 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.


26. Can we use two databases into a single application?
A. 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?
A. 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?
A.  Modules are often placed in the lib folder.
29. Where should you put code that is supposed to run when your application launches?
A. 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?
A. 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?
A. 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. 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? 
A.  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. 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?
A. 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?
A. 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.
A.  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?
A. 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?
A.  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. (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.
  1. # p021ranges.rb  
  2. =begin  
  3.   Sequences have a start point, an end point, and a way to  
  4.   produce successive values in the sequence  
  5.   In Ruby, sequences are created using the ".." and "..."  
  6.   range operators.  
  7.   The two dot form creates an inclusive range.  
  8.   The three-dot form creates a  range that excludes the specified  
  9.   high value  
  10.   The sequence 1..100000 is held as a Range object  
  11. =end  
  12. digits = -1..9  
  13. puts digits.include?(5)          # true  
  14. puts digits.min                  # -1  
  15. puts digits.max                  # 9  
  16. 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. (1..10) === 5       -> true  
  2. (1..10) === 15      -> false  
  3. (1..10) === 3.14159 -> true  
  4. ('a'..'j') === 'c'  -> true  
  5. ('a'..'j') === 'z'  -> false 
(Source: http://rubylearning.com/satishtalim/ruby_ranges.html)

40. How can you implement method overloading?
A. 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.
  1. # The Rectangle constructor accepts arguments in either  
  2. # of the following forms:  
  3. #   Rectangle.new([x_top, y_left], length, width)  
  4. #   Rectangle.new([x_top, y_left], [x_bottom, y_right])  
  5. class Rectangle  
  6.   def initialize(*args)  
  7.     if args.size < 2  || args.size > 3  
  8.       # modify this to raise exception, later  
  9.       puts 'This method takes either 2 or 3 arguments'  
  10.     else  
  11.       if args.size == 2  
  12.         puts 'Two arguments'  
  13.       else  
  14.         puts 'Three arguments'  
  15.       end  
  16.     end  
  17.   end  
  18. end  
  19. Rectangle.new([10, 23], 4, 10)  
  20. 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?
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))
but
(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?
A.  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
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?
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 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 ?
A. 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
   end
   def a2
   end
end
module B
   def b1
   end
   def b2
   end
end

class Sample
include A
include B
   def s1
   end
end

samp=Sample.new
samp.a1
samp.a2
samp.b1
samp.b2
samp.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?
A)  Generally three levels are there:
  1. Eager loading: you do everything when asked. Classic example is when you multiply two matrices. You do all the calculations. That's eager loading;
  2. 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
  3. 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:
  1. Load every single image required before you render the page (eager);
  2. Load only the displayed images on page load and load the others if/when they are required (lazy); and
  3. 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?
A)  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.
#!/usr/bin/ruby
class Example
   VAR1 = 100
   VAR2 = 200
   def show
       puts "Value of first Constant is #{VAR1}"
       puts "Value of second Constant is #{VAR2}"
   end
end

# Create Objects
object=Example.new()
object.show

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?

A) 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? 
A)  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?
A)  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`
   end
 end 
And It should work.

51.  What is the difference between Observers & Callbacks ?
A)   A callback is more short lived: You pass it into a function to be called once. It's part of the API in that you usually can't call the function without also passing a callback. This concept is tightly coupled with what the function does. Usually, you can only pass a single callback..

Example: Running a thread and giving a callback that is called when the thread terminates.
An observer lives longer and it can be attached/detached at any time. There can be many observers for the same thing and they can have different lifetimes.

Example: Showing values from a model in a UI and updating the model from user input.

52. What is a sweeper in rails?
A) Sweepers are the terminators of the caching world and responsible for expiring caches when model objects change. They do this by being half-observers, half-filters and implementing callbacks for both roles. You can get more Informations here. 

53. 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.

54. Is it possible to embed partial views inside layouts? How?
A) Yes it is possible. You Embed partial views inside the file /app/views/layout/application.html.erb and then whenever you render any page this layout is merged with it.

55. 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.” 
All commands available for rails are listed here

56. What is Polymorphic Association?
AIn Rails, Polymorphic Associations allow an ActiveRecord object to be associated with multiple ActiveRecord objects. A perfect example for that would be comments in a social network like Facebook. You can comment on anything on Facebook like photos, videos, links, and status updates. It would be impractical if you were to create a comment model (photos_comments, videos_comments, links_comments) for every other model in the application. Rails eliminates that problem and makes things easier for us by allowing polymorphic associations.

Friends i tried to cover up as much as possible questions and answers over here in this page.  Hope you guys like it. I will keep updating more questions and answers. Keep in touch. All the best.

(Note: Interviewer may not ask the exact questions mentioned here in this section. I have just tried to give some overall idea what you may face during the time of Interview. Also try to google out more articles like this. More opinions, suggestions, Q&A's will be always highly  appreciable.)

Candidates searching for a Business Analyst Position may also like this set of Interview Questions 

Sources used to Prepare this page:

http://ruby.megasolutions.net/Megasolution

http://anilpunjabi.tumblr.com/post/25948339235/ruby-and-rails-interview-questions-and-answersAnils Link

http://theprofessionalspoint.blogspot.in/2013/02/basic-ruby-on-rails-ror-interview.htmlThe Professional Point

http://puneetpandey.com/tag/ruby-on-rails-interview-questions/Puneets Blog

http://interviewquestionsanswers.org/forum/topic-1005-ruby-on-rails-interview-questions-and-answers-page-1.htmlInterview Questions & Answers

http://blog.sandeep.me/2012/05/ruby-on-rails-interview-questions.htmlSandeeps Blog

http://careerride.com/ruby-on-rails-interview-questions.aspxCareer Ride

http://www.psteiner.com/2013/02/preparing-for-ruby-on-rails-job.htmlRuby On Rails Job

http://meet2ravi.blogspot.in/2012/12/ruby-question-and-answer.htmlRavi's Blog

http://www.tutorialspoint.comTutorial Point

http://rubylearning.comRuby Learning

http://www.stackoverflow.comStack Overflow

ruby.railstutorial.org/Rails Tutorial

guides.rubyonrails.orgRuby On Rails Guide

www.sitepoint.com/learn-ruby-on-rails/Site Point

www.rubyonrailstutorials.comRuby On Rails Tutorial

 And many others. 

Yes Don't forget to Comment and share if these collections helpful for you. :)

Hey I have started a new blog Youtharena. I have a mission of empowering the youths to create their history. You can read my latest trending article on Youth Arena.

How to deal with haters in an effective way
   
What is empathy? 10 ways to be empathetic