Skip to main content

ROR INTERVIEW QUESTIONS


What are ruby gems?
This is a very open ended question and you might be better of to start with the basics first:
- A gem is nothing more than a piece of ruby code packaged as a library so that it can be imported and used by others in their programs.
- A Ruby gem is therefore simply a library that is written in the ruby programming language. 
- You can add that you often look for ruby gems on rubygems.org. If you have downloaded any recent gems it might be a good idea to mention those. Some of the popular Ruby gems that your interviewer will likely be faimilar with are:
> rails
> activerecord
> rake
> activeadmin
- Finally Rubygems is the name of the project that wrote the “gem” ruby library. [You need not mention this during the interview]

What is the difference between a Symbol and String?
Symbols and string are used interchangeably by various developers and their usage within gems can be confusing at times. You can think of Symbols as faster & immutable strings.
Once a string is used up it is marked for cleaning by the garbage collector but it is not cleaned up immediately and it cannot be reused.
Symbols live for the duration of the session. You might say that this leads to increased memory usage however by keeping the symbol alive a bit longer it can be reused again. 
Here’s a terminal irb session that will provide more insight. 
puts :"I am a symbol".object_id
457908

puts :"I am a symbol".object_id
457908

puts :"I am a symbol".object_id
457908

puts "I am a string".object_id
70343000106700

puts "I am a string".object_id
70343000094220
Notice that the object_id stays the same when symbols are created. This happens because the ruby interpreter uses the same heap memory location each time. The symbol was never completely released.
However, in the case of strings the memory is marked for cleanup each time and a new memory is allocated. 
Another big difference is that strings can be modified. They are mutable.
So, this would work:
puts "I am a string" << " for you"
I am a string for you
However, symbols are immutable. 
So, this would throw an error:
puts :"I am a symbol" << :" for you"
NoMethodError: undefined method `<<' for :"I am a symbol":Symbol

from (irb):16
from /Users/anilo/.rvm/rubies/ruby-1.9.3-p0/bin/irb:16:in `<main>'
1.9.3p0 :017 > puts :"I am a symbol" << " for you"
NoMethodError: undefined method `<<' for :"I am a symbol":Symbol


What is the purpose of yield?
The interpreter essentially invokes a separate piece of code and places it in the location. You might say it is similar to a method calling another method. Let’s understand a little bit of background about where yield might be useful first. 
The Rails framework encourages you to write code that is DRY (Don’t Repeat Yourself).
Developers often write common code in a central file and then they write the custom code in the specific files. Let’s say you are building a web application and you want all pages to have a common header, a common footer, the same “Welcome user-name!” message.
You can put all this common code in your application.html.erb file.
<html> .... common page title
.. standard header...
<body>
..common page title,
<%= yield %>
..footer code can go here... </body>
</html>
The rest of the custom code can go in your specific file. Say the page you are creating is the list of articles. Then in your implementation file you would just write the code for pulling in the articles and the final page displayed to the user would be your custom code which will be placed instead of the <%= yield %> code in the application.html.erb file.

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.
Another example can be found here:
class DemoClass 
@@my_var = nil
  def initialize
    @@my_var = "hello world"
  end
  def my_var
    puts @@my_var
  end
end
class Demo2Class < DemoClass
  def initialize
    @@my_var = "goodbye world"
  end
end
demo1 = DemoClass.new
demo1.my_var
demo2 = Demo2Class.new
demo2.my_var
demo1.my_var
The output would be as shown below:
hello world
goodbye world
goodbye world
This may appear strange at first, but really all it shows is that the variable my_var is shared across both object instances.

How do you define instance variables?
Instance variables are defined using single @ symbol.
@foo = "Hello"
Within a class they can be declared as below:
class Animal
attr_accessor :name, :age
end
Next you can query an object instance to find which instance variables it has.
anim = Animal.new
anim.instance_variables 
=> [ ]
anim.name="John"
anim.age = 3
 => [:@age, :@name] 
In the above case we did not put the @ symbol before the instance variables but it is implied. 
How do you define global variables?

 Global variables are defined using single $ symbol.
$foo = 5
It can be declared anywhere and used anywhere. 
Generally you shouldn’t declare too many global variables but sometimes it makes sense to do so. One nice feature of a global variable is that it can be used to trigger a procedure if it’s value changes.
trace_var :$foo, proc{puts "$foo is now #{$foo}"}
This set the tracking and the procedure is called whenever the value of $foo changes.
$foo=7
$foo is now 7
 => 7 
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 Album.new is called.
class Album
  def initialize(name, artist, duration)
    @name     = name
    @artist   = artist
    @duration = duration
  end
end
How can you dynamically define a method body?
An instance method can be defined dynamically with
Module#define_method(name, body),
where name is the method’s name given as a Symbol, and body is its body given as a Proc, Method, UnboundMethod, or block literal. This allows methods to be defined at runtime, in contrast to def which requires the method name and body to appear literally in the source code.
class Conjure
def self.conjure(name, lamb)
define_method(name, lamb)
end
end
# Define a new instance method with a lambda as its body
Conjure.conjure(:glark, ->{ (3..5).to_a * 2 })
Conjure.new.glark #=> [3, 4, 5, 3, 4, 5]
Module#define_method is a private method so must be called from within the class the method is being defined on. Alternatively, it can be invoked inside class_eval like so:
Array.class_eval do
define_method(:second, ->{ self.[](1) })
end
[3, 4, 5].second #=> 4
Kernel#define_singleton_method is called with the same arguments as Module#define_method to define a singleton method on the receiver.
File.define_singleton_method(:match) do |file, pattern|
File.read(file).match(pattern)
end
File.match('/etc/passwd',/root/) #=> #<MatchData "root">
What is a Range?
Range is a great way to declare continuous variables. You should use it to declare arrays and other types of collections. 
range1 = (1..4).to_a
 => [1, 2, 3, 4] 
puts range1
1
2
3
4
You can also create strings in this format and it fills in the interim values automatically.
range2 = ('bar'..'bat').to_a
puts range2
bar
bas
bat
Since the end result of using range is an array you can also iterate over it just like any other array.
range2.each do |str|
   puts "In Loop #{str}"
end
This produces the result as shown below:
In Loop bar
In Loop bas
In Loop bat
How can you implement method overloading?
This one’s a tricky question. If you have a background in Java then you must know that method overloading is simply multiple methods with same name but different signatures/parameters.
In the case of Ruby method overloading is not supported. 
However, it does support the overall goal of passing variable number of parameters to the same method. You would implement it like this:
class MyClass  
  def initialize(*args)  
    if args.size < 2  || args.size > 3  
      puts 'This method takes either 2 or 3 arguments'  
    else  
      if args.size == 2  
        puts 'Found two arguments'  
      else  
        puts 'Found three arguments'  
      end  
    end  
  end  
end  
The output can be seen here:
MyClass.new([10, 23], 4, 10)  
Found three arguments
MyClass.new([10, 23], [14, 13]) 
Found two arguments
SO: You can get the same effect as method overloading but you just have to manage the number of variables inside your method itself.
What is the difference between ‘&&’, ‘and’ and ‘&’ operators?
The ‘&&’ and ‘and’ are both logical and statements. They ‘&&’ operator has higher precedence though. Here’s an example of illustrate this in more detail:
foo = 3
bar = nil
a = foo and bar
# => nil
a
# => 3
a = foo && bar
# => nil
a
# => nil
Notice how the statement ‘a = foo and bar’ actually behaves like ‘(a = foo) and bar’
How can you create setter and getter methods in Ruby?
The setter and getter methods can be created manually by the developer or it can be auto-generated by Ruby using the attr_accessor method specifier.
class Animal
   attr_accessor :name, :age
end
anim = Animal.new
 => #<Animal:0x007f8ea20841d8> 
anim.age = 3
 => 3 
anim.name = "Steve"
 => "Steve" 
puts anim.name, anim.age
Steve
3
Of course you can achieve the same result by implementing all the setter and getter methods like this as well:
class Animal
  def name # this is the getter method
    @name
  end
  def name=(name)  # this is the setter method
    @name = name
  end
#...same for age...
end
What is the convention for using ‘!’ at the end of a method name?
The ! indicates that the method is about to change the object itself.
Here’s an example:
foo = "A TEST STRING"  # a string called foo

foo.downcase!     # modifies foo permanently
a test string

puts foo          # prints modified foo
a test string
Similarly if you did not want the object to be changed you could have something simple like:
foo2 = "A 2nd Test String"  # a string called foo

foo2.downcase     # modifies foo temporarily
a 2nd test string

puts foo2 nbsp;    # prints original foo
A 2nd Test String
What is a module?
A module is like a class. Except that it can’t be instantiated or subclassed.
In OOP paradigm you would store methods & variables that represent variables in a single class. Say you want to create an Employee representation then the employee’s name, age, salary, etc. would all go inside a Employee class, in a file called Employee.rb
Any methods that act on those variables would also go inside that class.
You can achieve the same effect by putting all the variables and methods inside a Employee module:
module Employee
..variables.
...methods
end
The main difference between the class & module is that a module cannot be instantiated or subclassed.
Module are better suited for library type classes such as Math library, etc. 
Does Ruby support multiple inheritance?
Ruby does not support multiple inheritance.
How can you achieve the same effect as multiple inheritance using Ruby? What is mixin?
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.
Here’s an example:
module Debug
  def whoAmI?
    "I am #{self.to_s}"
  end
end

class Photo
 include Debug
end

ph = Photo.new

"I am : #<Photo:0x007f8ea218b270>"
As you can see above the class Debug and it’s method “whoamI?” were mixed-in (added) with the class Photo.
That’s why you can now create an instance of the Photo class and call the whoAmI? method.
ph.whoAmI?
 => "I am : #<Phonograph:0x007f8ea218b270>" 
How will you implement a singleton pattern?
Singleton means single instance. 
So, the goal of a singleton pattern is to write a class definition but only allow the creation of the single instance of that object. 
This can be achieved nicely with the singleton gem as shown below:
require 'singleton'
 class Logger
  include Singleton
  def initialize
    @log = File.open("logfile.txt", "a")
  end
  def log(msg)
    @log.puts(msg)
  end
end
Adding the singleton as a mixin to the 
Logger.instance.log('This is just a test message')
The code above will create a single instance of Logger and simply put the message in the logger file.
Singleton patterns are mostly used for DB instance, Logger instance, etc. —- cases where there should be ONE and only ONE instance of the object that is used. 
Sometimes you might like to actually hold on to the logger object and use it everywhere you can do so by the following command:
logObj = Logger.instance
Notice you cannot use the Logger.new to create an object instance because this is a singleton object and therefore calling ‘new’ would fail.
How will you implement an observer pattern?
Let’s review first what an observer pattern is all about.  
The observer pattern (sometimes known as publish/subscribe) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.
You might have used them in other programming languages as listener objects. You use them whenever a button is clicked on the screen and a method gets called automatically. 
As in the case of the singleton pattern, the observer pattern is also implemented by mixing in a module. 
In the Ruby implementation, the notifying class mixes in the Observable module, which provides the methods for managing the associated observer objects.
And, the observers must implement the update method to receive notifications.
Here’s an example. Say you want to send an SMS alert to users if a company stock drops then you can do something like this:
require "observer"
require "observer"
class Ticker # Periodically fetch a stock price
include Observable
attr_accessor :price
def initialize symbol, price
@symbol = symbol
@price = price
end
def run
lastPrice = nil
loop do
@price = @price+Random.rand(11)
print "Current price: #{price}\n"
if @price != lastPrice
changed # notify observers
lastPrice = @price
notify_observers(Time.now, @price)
end
end
end
end
class Warner
def initialize ticker
ticker.add_observer(self) # all warners are observers
end
end
class SMSAlert < Warner
def update time, price # callback for observer
print "--- #{time.to_s}: SMS Alert for price: #{price}\n"
end
end

class EmailAlert < Warner
def update time, price # callback for observer
print "+++ #{time.to_s}: Email Alert Price changed to #{price}\n"
end
end
Now let’s initialize the classes and run them:
ticker = Ticker.new("MSFT", 307)
SMSAlert.new(ticker)
EmailAlert.new(ticker)
ticker.run
Current price: 312
--- 2012-02-22 01:26:04 -0800: SMS Alert for price: 312
+++ 2012-02-22 01:26:04 -0800: Email Alert Price changed to 312
Current price: 321
--- 2012-02-22 01:26:04 -0800: SMS Alert for price: 321
+++ 2012-02-22 01:26:04 -0800: Email Alert Price changed to 321
Current price: 323
--- 2012-02-22 01:26:04 -0800: SMS Alert for price: 323
+++ 2012-02-22 01:26:04 -0800: Email Alert Price changed to 323
Current price: 329
--- 2012-02-22 01:26:04 -0800: SMS Alert for price: 329
+++ 2012-02-22 01:26:04 -0800: Email Alert Price changed to 329
What is the purpose of environment.rb and application.rb file?
There are two files where variables and configuration settings are stored. 
- config/environment.rb : Environment settings go here
- config/application.rb : Application level global settings go here
config.time_zone = 'Central Time (US & Canada)'
config.i18n.default_locale = :de
config.filter_parameters += [:password] # ensures that passwords are not logged
The same file is also used for configuring various environment settings such as:
config.action_mailer.smtp_settings # various email settings go here
What is the purpose of config/environments/development.rb file?
You would specify various config settings the development environment in this file.
 config.action_controller.perform_caching = false # to enable caching
This is because you typically do not want to enable caching in the development environment. 
The same config setting in the production environment would be equal to true. 
How can you define a constant?
Create a new file as shown below under: config/initializers/my_constants.rb
COLORS = ['white', 'red', 'green']
How can you define a custom Exception?
How can you fire a method when a module is included inside a class?
Fire a method inside a class is very simple.
Say you have a module file trig.rb:
module Trig
PI = 3.141592654
def Trig.sin(x)
# ..
end
def Trig.cos(x)
# ..
end
end
Now you simply import this module inside your class and invoke the method using the “module.method_name” syntax as shown below
require "trig"

class myclass
y = Trig.sin(Trig::PI/4)
This type of invocation ensures that the right module method gets called.
What is the default access modifier (public/protected/private) for a method?
By default all methods are public, except the initialize(constructor) method.
You can make methods private using this declaration within your class:
class MyClass
    def method_public_here
    end
    private# all methods that follow will be made private: not accessible for outside objects
    def method_private_here
    end
  end
How can you call the base class method from inside of its overridden method?
If you are inside the overridden method in the derived class then a simple call to super will call the right method in the base class
class Parent
def try_this()
puts "parent"
end
end

class Child < Parent
def try_this()
super()
puts "child"
end
end

ch = Child.new
ch.try_this()
This generates the output
parent
child
Now if you just want to call the base class without calling the derived class then the best way to do that is to simply assign an alias to the parent method like this:
class Parent
def knox
puts 'parent'
end
end
class Child < Parent
alias_method :parent_knox, :knox
def knox
puts 'child'
end
end
ch = Child.new
ch.parent_knox
ch.knox
This allows you to call the base class method with the alias parent_knox and the derived class method knox can be called directly.
parent
child
Define the Rails MVC implementation using an example.
The MVC framework is an age-old architecture pattern that works very well for most applications. Rails has adopted the MVC pattern in its inherent design.
Stated Simply:
a) Model — is where the data is — the database
b) Controller — is where the logic is for the application
c) View — is where the data is used to display to the user
Let’s look at an example in Rails.
Here’s a very straight forward usage diagram for the MVC framework. 
What is scope? (or named_scope in Rails 2.x).
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.
Say you typically access content as shown below:
@posts = Post.where("published_at IS NOT NULL AND posts.published_at <= "+ Time.now)
Ruby offers you a nice way to put the where condition inside a scope statement as shown below.
class Post < ActiveRecord::Base
  scope :published, lambda { 
    { :conditions =>
      ["posts.published_at IS NOT NULL AND posts.published_at <= ?", Time.now]
    }
  }  
  scope :recent, :order => "posts.published_at DESC"
end
Now you can simply access the published posts as: Post.published
@posts = Post.published
Also, you can access recent posts as 
@recent_posts = Post.recent

Can you give an example of a class that should be inside the lib folder?
Modules are often placed in the lib folder. 
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.
What deployment tool do you use?
Capistrano is a popular deployment tool.
How can you migrate your database schema one level down?
The rake tool does most of the migrations. 
It has this nifty syntax to go back one step:
rake db:rollback
If you want to rollback all the way to the beginning you would use:
rake db:reset
This would drop the database, recreate the Database and load the current schema into it
If you want to rollback multiple steps at the same time you would use:
rake db:rollback STEP=3
To rollback all the way and if you are not worried about losing the data then you can drop the database completely with purge like this:
rake db:purge
What is a sweeper?
Sometimes you want to have control over how often and when the cache expires. 
Sometimes it is a good idea to have the system determine that on a logical basis. Say you have a list of product on your site and you want to reload the cache each time a new product is added/updated/deleted, then you can achieve this by using the sweeper. 
class ProductSweeper < ActionController::Caching::Sweeper
  observe Product# This sweeper is going to keep an eye on the Product model 
  # If our sweeper detects that a Product was created call this
  def after_create(product)
    expire_cache_for(product)
  end
  # If our sweeper detects that a Product was updated call this
  def after_update(product)
    expire_cache_for(product)
  end
  # If our sweeper detects that a Product was deleted call this
  def after_destroy(product)
    expire_cache_for(product)
  end
  private
  def expire_cache_for(product)
    # Expire the index page now that we added a new product
    expire_page(:controller => 'products', :action => 'index')
    # Expire a fragment
    expire_fragment('all_available_products')
  end
end
How can you implement caching in Rails?
Rails offers multiple ways to cache content.
Fragment caching is my favorite because it gives you the choice to fragment to pull a portion from the cache and the remaining from a real-time DB call. 
Say you wanted to show all the orders placed on your website in real time and didn’t want to cache that part of the page, but did want to cache the part of the page which lists all products available, you could use this piece of code:
<% Order.find_recent.each do |o| %>
  <%= o.buyer.name %> bought <%= o.product.name %>
<% end %>
<% cache do %>  All available products:
  <% Product.all.each do |p| %>
    <%= link_to p.name, product_url(p) %>
  <% end %>
<% end %>
Another technique that works well for static pages is page caching. This technique is often used for home pages and is super fast.
class ProductsController < ActionController
   caches_page:index
  def index
    @products = Products.all
  end
end

What is a filter? When it is called?
Filters are methods that are called either before/after a controller action is called. 
Say a user requests a controller action such as userdashboard/index
In such a case a filter can be setup so that the UserDashboard/index page is only accessible to loggedin users by adding the following lines towards the beginning of the page:
class UserDashboardController < ApplicationController

  before_filter :confirm_logged_in,  :except => [:login, :attempt_login, :logout]
 
def index
....
end

def login
....
end

def attempt_login
....
end

def logout
....
end

end  
In the code above the condition “confirm_logged_in” is checked before all actions, except login, logout & attempt_login. 
After filters (after_filter) are not used too much but they have the effect of executing some code after a particular action has completed. 
Think of them like triggers that get executed automatically — just like a database trigger. 
What do controllers do in Rails?
Once a request comes into the Rails stack, it goes to the routes table to determine which controller and action should be called. 
Once a controller action is determined the request is routed to the controller and it does the needed processing by connecting with the DB if needed and then it sends control to the View to render the output. 
So, really the flow for Rails goes somewhat like this:
Customer-> Routes-> Controller -> Model(DB) -> Controller -> View -> Customer
How can you divide your controllers into separate modules?
What is RESTful routing?
Routing is fun. If you have ever dealt with IIS you will fall in love with RESTful routing. Here’s how it works. 
Say you want your users to have access to certain pages such as:
/photos/new
/photos/1/edit
/photos/1
And, you want the right controller to get called.
And, you want the right view to get rendered.
All this is made possible with a single entry in the routes.rb file as shown below:
resources :photos 
In Rails, a resourceful route provides a mapping between HTTP verbs and URLs to controller actions. By convention, each action also maps to particular CRUD operations in a database. The single entry in the routing file creates seven different routes in your application, all mapping to the Photos controller:
How can you list all routes for an application?
rake routes -- will display all routes for an application.
How can you send a multi-part email?
Nowadays most email clients support HTML email, however there are still some old Blackberry phones that prefer emails the ‘ol text way. 
Therefore it is important to send emails both as HTML and text. This technique is called multi-part emails. 
The ActionMailer class (included in Rails 3.0) does a great job of sending both text and HTML emails out to the end user at the same time. 
By default Rails sending an email with plain/text content_type, for example:
# app/models/notifier.rb
def send_email(email)
subject email.subject
from email.from
recipients email.recipients
sent_on Time.now
body :email => email
end
Next let’s update the view in : app/views/notifier/send_email.html.erb
Welcome to here:
The sent email is a plain text email
Date: Thu, 5 Aug 2010 16:38:07 +0800
From: RailsBP
To: flyerhzm@gmail.com
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8

The link url is just displayed as a plain text because of the email content_type.
text/html
If we want the email clients to display link url as html format, we should change the content_type to text/html in the app/models/notifier.rb file
def send_email(email)
subject email.subject
from email.from
recipients email.recipients
sent_on Time.now
content_type "text/html"
body :email => email
end
Now the sent email is a html formatted email
Date: Thu, 5 Aug 2010 17:32:27 +0800
From: RailsBP
To: flyerhzm@gmail.com
Mime-Version: 1.0
Content-Type: text/html; charset=utf-8

Now the email client can display the link url correctly with html format.
The email header looks somewhat like this:
Content-Type: multipart/alternative;
boundary="----=_NextPart_000_002C_01BFABBF.4A7D6BA0"
Content-Type: multipart/alternative tells the e-mail program to expect different parts to follow, separated by a boundary which specified in quotation marks. Actually the boundary could be anything, though hyphens, equal signs, and underscores insure that the e-mail program won't try to display this boundary to the recipient.
------=_NextPart_000_002C_01BFABBF.4A7D6BA0
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: 8bit

What is the purpose of layouts?
Layouts are partial ruby/html files that are used to render the content pages. 
There are placed in the folder: app/views/layouts
Items that you would typically put in this folder are things like headers/footers, navigation elements, etc.
Here’s a sample layout file: /app/views/layout/application.html.erb
<html lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Learning System | <%= @page_title || 'Admin Area' %></title>
    <meta name="author" content="Anil Punjabi">
    <%= stylesheet_link_tag('public', 'admin', :media => 'all') %>
    <%= javascript_include_tag('application') %>
  </head>
  <body>
    <div id="header">
      <h1>Learning System</h1>
    </div>
    <div id="main">
      <% if !flash[:notice].blank? %>
      <div class="notice">
        <%= flash[:notice] %>
      </div>
      <% end %>
      <div id="content">
        <%= yield %>
      </div>
    </div>
    <div id="footer">
      <p id="copyright">&copy; / Anil Punjabi</p>
    </div>
  </body>
</html>

Then the contents of the index.html.erb would be placed above in the section shown under <% yield %> above and sent back to the user.
Is it possible to embed partial views inside layouts? How?
That is the purpose of layouts. 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.
What is the purpose of RJS?
How can you create a REST API for your application?
How can you define a new environment called ‘staging’?
What is Rake?
Rake is a popular ruby gem that makes the job of running tasks simpler. 
Rake is most often used for DB tasks, but it can be used for m
The common DB commands are:
rake db:migrate
rake db:reset
You can use cron to schedule rake tasks. 
Sometimes you would create a dataloader.rake file and put it in the lib/tasks folder so that it can be used to populate the database on startup.

What is Capistrano?
Capistrano is a popular deployment tool — it allows developers to push code from their desktop to the servers. 

What is a has and belongs to many association?
What is the difference between has_one and belongs_to?
A has_one relationship is used to define a 1:1 relationship between two objects.
Examples are:
  • A project has_one projectManager
  • A sandwich has_one buyer
  • A sandwich has_one seller
A belongs_to relationship on the other hand is used to define the reverse association for the same 1:1 relationship that is defined using the has_one keyword. 
class Employee < ActiveRecord::Base
has_one :office
end
class Office < ActiveRecord::Base
belongs_to :employee # foreign key - employee_id
end
The important thing to keep in mind is that you need to declare both associations in order for the relationships to work correctly.

How can you implement single table inheritance?
What is a polymorophic association?
A polymorphic association is what one would call “open-ended” association of one class with multiple objects. 
Let’s say you have a generic class called “Picture”.
Now this “Picture” class might be used to store Pictures for Employees, Products and Dogs. They all have pictures and they all are associated to the Picture class. 
Hence, this type of open-ended association is called “Polymorphic” association. 
Let’s see how we can declare them. 
class Picture < ActiveRecord::Base
belongs_to :imageable, :polymorphic => true
end
class Employee < ActiveRecord::Base
has_many :pictures, :as => :imageable
end
class Product < ActiveRecord::Base
has_many :pictures, :as => :imageable
end

class Dog < ActiveRecord::Base
has_one :picture, :as => :imageable
end 
Notice that the Dog object has a 1:1 relationship with the Picture class, whereas the Product class has a 1:many relationship with the Picture class.
This capability prevents the headache of having of declare new classes for each new type of Picture.
The polymorphic relationship would look somewhat like this.
What is eager loading?
Eager loading is a great optimization strategy to reduce the number of queries that are made against the DB.
Say you are finding 10 employees and then you are looking for their post codes. Then your query would appear something like this:
clients = Client.limit(10)
clients.each do |client|
  puts client.address.postcode
end
This may seem fine at first look but really this implementation leaves much to be desired. It makes 11 DB calls just to get the results.
Now you can optimize this query by making a slight change in the request like this:
clients = Client.includes(:address).limit(10)
clients.each do |client|
  puts client.address.postcode
end 
This new request makes two SQL calls like this:
SELECT * FROM clients LIMIT 10
SELECT addresses.* FROM addresses
    WHERE (addresses.client_id IN (1,2,3,4,5,6,7,8,9,10))
So, as you can see it really loads a lot more upfront and therefore it is called eager loading.


How can you eager load associated objects?
How does validation work?
Validation means checking to see if data  is good before it is stored in the database.
During signups and other such user input cases you want to check and be sure that the data is validated. In the past developers would often put this type of validation logic as triggers in the database.  
In an MVC architecture one can do validations at each level. 
You can do validations in the controllers but it is usually a good idea to keep your controllers skinny.
Views suffer from the javascript limitation because javascript can be disabled on the client side so they are not completely reliable.
The best way to manage validation is to put it in the model code. This model code is really the closest as you can be to the database and works very well for Rails applications.
Here are a few validation examples:
class Person < ActiveRecord::Base
  validates :name, :length => { :minimum => 2 }
  validates :points, :numericality => { :only_integer => true }  # only integer
  validates :age,  :numericality => { :greater_than => 18 } # greater than 18
  validates :email, :uniqueness => true
  validates :email, :confirmation => true  # this is to validate that the two email fields are identical
  validates :email_confirmation, :presence => true # this is to validate that the email confirmation field is not nil
In your view template you may use something like this:
<%= text_field :person, :email %> <%= text_field :person, :email_confirmation %>
How can you add a custom validation on your model?
Now custom validations takes it to the next step.
Say you want to confirm that the data meets certain criteria 
How can you implement a custom theme for your forms?
Why is fields_for used for?
What is the purpose of a helper method?
What is flash?
Flash  is simply a way to pass some value to the next action. 
Anything you place in the flash will be exposed to the very next action and then cleared out.
Here’s an example:
def destroy

section = Section.find(params[:id])      
section.destroy
     
flash[:notice] = "Section destroyed."
     
redirect_to(:action => 'list', :page_id => @page.id)    

end
Then wherever you want to use the flash you can write this code. I often put this snippet in the application.html.erb file, somewhere towards the top:
   <% if !flash[:notice].blank? %>        
<div class="notice">  
 <%= flash[:notice] %>

How can you install the missing gems that are required by your application in the simplest way?
bundle install
This command will install all dependencies and missing gems. It looks at your Gemfile to figure out what gems are needed by your application. 
How can you implement internationalization?
Ruby ships with i18n which is an internationalization gem. 
You need to create locale files and save them under the config/locales directory as:
en.yml
es.yml
fr.yml
The keys should match for each of these files. 
en:   main_page:     hello: “Hello”     welcome: “Welcome to   My Company” es:   main_page:     hello: “Hola”     welcome: “Bienvenido a Mi Empresa” fr:   main_page:     hello: “Salut”     welcome: “Bienvenue à  Mon Entrepriseâ€
 In your code you would need to specify that the text would be locale specific. So change it to something like this:
.content   %h1     = t("main_page.hello")
%p     = t("main_page.welcome")

How can you configure your application for different environments?
How can you instruct rails logger to ignore passwords and such fields while logging?
Test Frameworks
Ruby on Rails has a number of built-in and a few other third-party test frameworks. Here are a few sample questions on such frameworks:
Are you familiar with unit testing?
How does functional testing differ from unit testing?
Have you ever used a mocking framework?
Are you familiar with BDD using RSpec or Cucumber?
What is an alternative to using test fixtures?
How can you reuse part of a text fixture?
How do you specify associations in the test fixture yml files?
Plugins
Plugins are the principal mechanism to reuse code. The open-source community is at full-bloom when it comes about plugins. The Rails Plugins site has a really good list of such plugins from the community.
What plugin would you recommend for user authentication and authorization?
Devise works great with Rails. 
It supports OAuth authentication and therefore integrates nicely with Facebook. 

What plugin do you use for full-text search?
Sunspot supports full-text search capability and uses Solr as the back-end search engine to do so. 
You would include these two plugins in your gem file as shown below:
gem 'sunspot_rails'
gem 'sunspot_solr'

How can you implement a state machine?
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. 
How can you create a plugin?
You can read about how to create a rails plugin here:


How can you implement a search feature that searches for multiple models?
If you are using acts_as_solr for your search you will be able to use multi_solr_search to enable search across multiple models. 
Also, you can configure Sunspot/Solr to support search across multiple models. Here’s a post about it
Sphinx, another powerful search server can be used to search across multiple models and it works great. 
How can you upload a file to a server?
Paperclip is the best solution to manage file uploads to a server.
It can also help you with multiple file uploads and associate it with ActiveRecord.
There are also good examples online that show how you can make rotating sliders with the paperclip images.
Another nice solution is using carrier_wave gem. 
The nice thing about carrier_wave is that it has good documentation on how to integrate with S3, Google & Rackspace for file storage.
You can achieve the same file storage capability with Paperclip as well though. 
SEO Related Questions
How can you generate sitemaps for your Rails site?
You can use dynamic_sitemaps gem to generate sitemaps
How can you show search user friendly urls instead of using only numeric ids?
The simplest way to do this is to use the gem FriendlyID.
It gives you the ability to specify a friendly URL for pages so that instead of the standard page URLs like:
You can build pages such as:
How can you create page titles and metadata for your pages?
You can use the Headliner plugin for adding page titles.
You can use the MetaMagic plugin to add meta tags.
How can you create breadcrumbs on your pages?
Gretel is a great plugin to introduce breadcrumbs in your Rails application.
Another very simple implementation is breadcrumb_on_rails.
Architecture Related Questions
This questions can be from different angles like: quality, security, scalability, manageability, interoperability, reusability and all the other ilities you name! Here are a few example questions:
Is Rails scalable?
Yes Rails gives you complete freedom to use all traditional means of scaling an application. Things like memcached, caching full pages, caching fragments are all supported. 
You can use any standard CDN to serve your media and static content as well. 
Database scaling using sharding is supported. 
Finally heroku makes your life easier by giving you the flexibility to scale up/down based on your need. Mostly websites have a peak time during which you need more servers and then there is a sleep time. Heroku makes that on-demand scaling process simpler. Companies such as HireFireApp.com makes the autoscale process easier.
What are the key deployment challenges?
heroku makes deployment easy.
Things that I sometimes run into are:
> Mismatched gem versions between local and production environment
> Some lessons learned:
»» Use image_tag helper each time
»» Specify root path in ENV variable
»» Configure assets pipeline by setting: config.assets.enabled = true in the config/application.rb file
Configure Capistrano script to precompile assets 
Here’s a nice video about Assets Pipeline
How can you safeguard a rails application from SQL injection attack?
Rails already has the logic built into it to prevent SQL injection attacks if you follow the right syntax. 
Say you are trying to authenticate a user based on their login and password you might be tempted to use a syntax as below:
User.first("login = '#{params[:name]}' AND password = '#{params[:password]}'")
If an attacker enters ’ OR ‘1’=‘1 as the name, and ’ OR ’2’>’1 as the password, the resulting SQL query will be:
SELECT * FROM users WHERE login = '' OR '1'='1' AND password = '' OR '2'>'1' LIMIT 1 
This will simply find the first record in the database, and grants access to this user.
To prevent this type of SQL injection simply use the following format.
  User.where("login = ? AND password = ?", entered_user_name, entered_password).first
OR
User.where(:login => entered_user_name, :password => entered_password).first
How can you secure a rails application?
Rails has a lot of in-built capabilities to deal with common web-security issues. 
> SQL Injection
> Cross-Site 
> Session fixation and Session hijacking
> Captcha
Follow this useful security guide
How can rails engage with a SOA platform?
Overall Community Questions
Can you tell me a few good community resources for Rails?
Stackoverflow, Github, various Meetup groups
Where would you reach out to get the community to answer your questions?
Stackoverflow and meetup groups.
What books can help me understand the basics of Ruby on Rails?
Best way to learn Ruby on Rails is to read every page from Michael Hartl’s : Ruby on Rails Tutorial  Ruby on Rails  and actually write code with each chapter. There’s no better way to learn than to actually code it !!!
For those that enjoy the visual way of learning things you might also enjoy the video series from Michael Hartl’s : Ruby on Rails Tutorial and LiveLesson Video Bundle
I used both to get a good grasp of the basics. 
Everything else was just practice and networking with friends.

Ruby Questions
Q: What is the highest level in the object model?
A:
BasicObject

Q: Is everything in Ruby an object?
A: Methods are not objects. Blocks are not objects. Keywords are not objects. However, there exist Method objects and Proc objects, and some keywords refer to objects.

Q: Which core object includes the
Kernel module?
A:
Object

Q: What can you say about an identifier that begins with a capital letter?
A: It is a constant.

Q: What is a DSL and how does it pertain to Ruby?
A: A Domain Specific Language is an API that allows a developer to solve a problem or represent data more naturally than they might otherwise. The flexible nature of Ruby's syntax and the ability to alias and alter existing methods and classes makes it conducive to creating rich DSL's.

Q: What is duck typing and how does it pertain to Ruby?
A: That an object may be acted upon even if it isn't the expected type as long as it looks and behaves like the expected object. This is a characteristic of Ruby because the lack of type checking of parameters makes this an effective programming technique.

Q: Is Ruby a statically typed or a dynamically typed language?
A: Dynamically typed since type checking is done at runtime.

Q: Is Ruby a strongly typed or a weakly typed language?
A: Strongly typed since an object's type is checked before an operation is performed on it.

Q: What does it mean to coerce an object? Why would you do it?
A: To coerce an object means to force it into an expected type. One might do this in order to try and force an unknown object type into the expected type or format required by the operation. This is a common practice involved in duck typing.

Q: What is the difference between a statement and an expression in Ruby?
A: All statements are expressions in Ruby since all statements return a value.
String
Q: Why might you want to avoid using string literals within loops?
A: A new object is created for every string literal even when the values are identical. Consider using variables or symbols instead.

Q: Does
String include the Enumerable module?
A: No.

Q: What method might you use to enumerate over a string?
A:
String#each_char

Q: What is the difference between a character literal such as
?A and a string literal such as "A"?
A: There is no difference.
Symbol
Q: Describe a symbol.
A: Symbols are scalar value objects used as identifiers, mapping immutable strings to fixed internal values.

Q: Why are symbols typically used as hash keys instead of strings?
A: Strings are mutable while symbols are immutable. Though Ruby internally makes an immutable copy of a string when used as a hash key, comparing two symbols is faster than comparing two
String objects. This is also a convention.
Numeric
Q: Symbols are immutable objects. Name another immutable core Ruby object.
A:
Fixnum

Q: What happens when a value becomes too big for
Fixnum?
A: It is automatically converted to a
Bignum.

Q: What is the superclass of
Fixnum?
A:
Integer

Q: What is the superclass of
Integer?
A:
Numeric

Q: What numeric class might you use to avoid the rounding error arising in the use of binary floating-point arithmetic?
A:
BigDecimal
Array
Q: How does the %W syntax differ from the %w syntax?
A: With
%W it is possible to define an array containing string interpolation.
Hash
Q: Name at least one synonym for Hash#key??
A:
Hash#has_key?, Hash#include?, Hash#member?

Q: How might you specify a default value for a hash?
A: Pass the default values as arguments to
::new on initialization or change the default directly with the method Hash#default. You may also provide a default at the time of query with Hash#fetch.

Q: Does
Hash use #== or #eql? to compare hash keys?
A:
#eql?

Q: In what order are the values of a hash iterated?
A: The order in which they were inserted.

Q: What is the synonym of
Hash#[]=?
A:
Hash#store

Q: Why can you safely use a string as a hash key, even though a string is mutable?
A: Because the interpreter makes a private copy of a string used as a hash key.

Q: Why might you use
Hash#fetch over Hash#[] when querying values in a hash?
A:
Hash#fetch provides options for handling the case where a key does not exist in the hash.

Q: When would you need to use
Hash#rehash?
A: After you mutate a mutable hash key.
Range
Q: What are two uses of ranges?
A: comparison, iteration
Regexp
Q: How might you include an expression within a Regexp literal?
A: Using
#{} just like as in a double-quoted string literal.

Q: What is the global variable for the last
Regexp match?
A:
$LAST_MATCH_INFO equivalent to $~
Operators
Q: What are two uses of the splat operator?
A: Explode or expand the elements of an array. Collect arguments of a parameter list into an array.

Q: What is the only operator which accepts three operands?
A: The conditional operator
?: (sometimes referred to as the ternary if operator).

Q: Which operator must be defined in order to implement the
Comparable module?
A:
<=>

Q: What is the difference between
#== and #equal??
A:
#== 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.

Q: What is the difference between
#== and #===?
A:
#== performs the generic comparison while #=== performs case equality comparison and is useful for providing meaningful semantics in case statements.

Q: What is the difference between
#== and #eql??
A:
#eql? is sometimes an alternate equality. Hash uses #eql? to test for hash key equality. Numeric types perform type conversion across #== but not across #eql?, thus #eql? performs a stricter comparison than #== in that case.

Q: Which binds more tightly?
&& or and
A:
&&

Q: Which binds more tightly?
&& or =
A:
&&

Q: Which binds more tightly?
and or =
A:
=

Q: Which binds more tightly?
&& or ||
A:
&&
Control Structures
Q: What is a statement modifier?
A: A condition which follows a statement such as with
x = 1 if a == true

Q: Does a while block define a new scope?
A: No.

Q: Does the case statement in Ruby have fall-through behavior?
A: No.

Q: What is the difference between
throw/catch and raise/rescue?
A:
throw and catch accept matching symbols as arguments and should be considered a control-flow structure where raise and rescue is used to raise and handle exceptions. throw and catch are not commonly used while exception handling with raise and rescue is used often.

Q: Does a
rescue block define a new scope?
A: No.

Q: What are some advantages of a case statement versus repeated
elsif statements?
A: It shows intent. It DRY's out the condition.

Q: What are some disadvantages of a case statement versus repeated
elsif statements?
A: The statement is typically resistant to modification without a complete refactoring of the entire control structure. The case statement can be confusing if multiple comma-separated expressions are associated with a single when clause.
Blocks and Iterators
Q: Name at least two classes which include the Enumerable module.
A:
Array, Hash, Range, IO...

Q: When might you use the
do/end syntax versus using the curly bracket syntax for a block?
A: The
do/end syntax for a block is commonly used for multi-line statements. An alternate convention is to use curly bracket syntax for blocks that return a value while using do/end syntax for blocks that change the state of the system somehow and do not return a value.

Q: What is an iterator?
A: An object that allows traversal of the elements of the container. In Ruby, an iterator is typically considered any method that uses the yield statement.

Q: How do you define block-local variables within a block's parameter list?
A: Variables that appear after a semicolon in a block's parameter list are guaranteed to be local to the block.

Q: What is the synonym of
Enumerable#include??
A:
Enumerable#member?

Q: Can a collection be modified while it is being iterated upon?
A: Yes.

Q: Is a block an object?
A: No. A block is a syntactic structure of the interpreter. A block can be converted to a Proc object.

Q: What is the synonym of
Enumberable#collect?
A:
Enumberable#map

Q: What is the synonym of
Enumberable#find?
A:
Enumberable#detect

Q: What is the synonym of
Enumberable#select?
A:
Enumberable#find_all

Q: What is the opposite of
Enumberable#select?
A:
Enumberable#reject

Q: What is the synonym of
Enumberable#inject?
A:
Enumberable#reduce

Q: Why might you use
#each instead of for/in?
A: 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.

Q: What happens if a block is passed two arguments but only accepts one argument?
A: Nothing. Only the first argument will be passed to the block.

Q: How is a block anonymous?
A: It doesn't have a name. It doesn't exist beyond it's execution unless converted to a Proc object.

Q: How does block invocation differ from method invocation?
A: Ruby will throw an exception if more than the expected number of arguments are passed to a method. A block will simply ignore the extra values.
Methods
Q: Does Ruby support method overloading?
A: No.

Q: How might you test the presence of a method?
A:
Object#respond_to? or Module#method_defined?

Q: What is the meaning of
self?
A: The current object.

Q: What does a bang
! at the end of a method signify?
A: That it should be with caution. Methods with this naming convention typically perform a mutation on the receiver object.

Q: What is a mutator method?
A: A method which alters the internal state of the object receiver.

Q: Is a method an object?
A: No, however, a
Method object is of course, an object.

Q: What is a predicate in the context of Ruby method naming conventions?
A: A method that answers a question posed by the method invocation or method name. Predicates typically return a boolean.

Q: Are instance methods public or private?
A: They are public by default. You can change their visibility using
Module#private, Module#protected, or back again using Module#public.

Q: When might you explicitly use the
return statement.
A: To return from a method prematurely.

Q: Why might you want to alias a method?
A: To create a synonym for an existing method that is more readable or appropriate in the context of some problems or to add functionality to an existing method.

Q: How might you send a message to a private method of a receiver object from outside the scope of the receiver object?
A:
Object#send

Q: How would you typically prevent future modifications to an object?
A:
#freeze

Q: How is the invocation of a private method different than the invocation of a public method from within its defining class?
A: It must be referenced in a functional manner without an explicit receiver object and not on the class object itself or on the current object
self.

Q: Can method names be capitalized?
A: Yes, but the convention is that they are not.

Q: What is the difference between private and protected methods?
A: A private method can only be called by any instance methods of the defining class or any subclasses and must be invoked in a functional style and not explicitly on
self such as with self.my_method. A protected method may be explicitly invoked by any instance of the defining class, and is not restricted to implicit invocation on self.

Q: What is a singleton method?
A: A method that is available only on a single object.

Q: How does
return differ from within a method than from within a block?
A:
return within a method returns from the method. return within a block returns from its lexically enclosing method.

Q: Are class methods public or private?
A: They are public by default. You can change their visibility using
Module#private_class_method and back again using Module#public_class_method.

Q: Does a method return a value if it does not contain an expression?
A: Yes, it returns
nil.

Q: If a method is declared outside a class or module definition at the top level, where does it live?
A: As a private instance method of
Object, whose value of self resolves to the special "main" object.

Q: What is the origin of the "keywords"
public, private, and protected?
A: They are instance methods of the
Module class. Since Class subclasses Module, these methods can be invoked without an explicit reference to self such as with self.private.

Q: How do you define a private class method?
A: Define the class method and call
Module#private_class_method with an argument as a symbol of the class method name.

Q: Name at least two ways to disable methods.
A:
undef method_name, Module#remove_method, Module#undef_method

Q: What is the difference between
Module#remove_method and Module#undef_method?
A:
Module#undef_method prevents any invocation of the method through an instance of
the class, while
Module#remove_method will remove the method definition from the class, but not prevent inherited methods of the same name from being invoked.

Q: Explain how Ruby syntax supports keyword arguments in parameters lists?
A: You can leave off the curly brackets from a hash in a parameter list, assuming it is the last argument in the list.
Procs and Lambdas
Q: What are the two varieties of Proc objects?
A: Procs and lambdas.

Q: What can be said about a method argument that is prefixed with
&?
A: It will refer to the calling block as a named Proc object. It must be the last argument in the parameter list.

Q: What is the main difference between procs and lambdas?
A: Calling a lambda is more akin to invoking a method where a return statement in a lambda will return from the lambda itself, instead of returning from the lexically enclosing method, as procs do. Adding to this notion, lambdas must be invoked with the exact number of arguments such as is required by method invocation, whereas procs are more flexible in receiving arguments.

Q: Does an object have to be a Proc object for a
& to be prefixed to it in a parameter list?
A: No,
& can appear before any object having a #to_proc method.

Q: What is the difference between Proc invocation and lambda invocation?
A: A block must be associated with lambda invocation. Lambdas must be invoked with the exact number of arguments such as is required by method invocation, whereas procs are more flexible in receiving arguments.

Q: When might you encounter a
LocalJumpError?
A: You might typically encounter this exception when attempting to yield when no block is given. You might also encounter this exception when attempting to return from a method that has already returned such as if you attempt to return from a Proc object whose lexically enclosing method has already returned.
Closures
Q: Describe a closure in Ruby.
A: 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.

Q: Does a closure in Ruby retain variables by value or by reference?
A: By reference; the closure also extends the lifetimes of its variables.

Q: A closure's reference to its variables is said to be dynamically bound. What does this mean?
A: The values of the variables are resolved when the Proc object is executed.

Q: Is it possible to alter a closure?
A: Yes, the binding of a closure can be altered using
#binding.
Method Objects
Q: What must you first do before you can invoke an UnboundMethod object?
A: Bind it to a receiver object using
UnboundMethod#bind.

Q: Are method objects closures?
A: No.

Q: How do you obtain a
Method object from an existing module/class?
A: Using
Object#method

Q: How do you obtain an
UnboundMethod object from an existing module/class?
A: Using
Module#instance_method
Constants
Q: Are constants public or private?
A: Public.

Q: What happens if you attempt to define a constant on a class from outside the class?
A: It defines successfully since constants are publicly accessible and assignable.

Q: What happens to a constant which is not assigned?
A: It does not exist.
Classes
Q: What is the difference between an instance variable and a class variable?
A: 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.

Q: Why must a class name begin with a capital letter?
A: Because the
class keyword creates a new constant that refers to the class and constants begin with a capital letter.

Q: Is
#initialize an instance method or a class method?
A: An instance method.

Q: What is the difference between a class variable and a class instance variable?
A: Class instance variables are instance variables of a class. Class instance variables cannot be used within instance methods.

Q: What is a singleton?
A: A class having only a single instance.

Q: How might you create a singleton?
A: By including the
Singleton module.

Q: Can you define accessor methods for class instance variables?
A: Yes, if they are defined as singleton methods of the class.

Q: Can classes be nested?
A: Yes.

Q: Is
#initialize public or private?
A: Private by default.

Q: What does
Class#allocate do?
A: It creates an uninitialized instance of a class.

Q: What is an eigenclass?
A: An anonymous class associated with an object. An object's singleton methods are instance methods of its associated eigenclass.

Q: What is the relationship between singleton methods and class methods?
A: Class methods are singleton methods of the eigenclass associated with the class object.

Q: What is
Class::new?
A: A class method of the
Class object which creates new classes.

Q: If
Class B is nested within Class A, and there exists a class method on A, does Class B then have access to this instance method on Class A?
A: No. Nesting one class within another does not give the inner class any special access to the methods or variables of the outer class.

Q: Are eigenclasses inherited?
A: The eigenclasses of an object are inherited from the eigenclasses of the superclass of the class object. An eigenclass of an object instance stands alone and does not inherit from any other classes.

Q: What happens to any return value of
#initialize?
A: It is ignored.

Q: What is a factory method?
A: An initialization method that creates specialized instances of a class.

Q: What is the method to run initialization code on copied instances of an object?
A:
#initialize_copy

Q: Does
#initialize_copy override #initialize?
A: No.

Q: What does it mean that
Object#dup and #clone perform shallow copies?
A: The instance variables of the copy are copied by reference rather than by value.

Q: What is the difference between
Object#dup and #clone?
A:
#clone copies the frozen state of an object and any singleton methods of an object while Object#dup does neither.
Modules
Q: What are two main functions of modules?
A: As mixins, as namespaces...

Q: Can a module be subclassed?
A: No.

Q: What happens when a class includes a module?
A: The instance methods of the module become instance methods of the class.

Q: What happens when an object extends a module?
A: The instance methods of the module become singleton methods on the object.

Q: What is the superclass of
Class?
A:
Module

Q: Why must module names begin with a capital letter?
A: Because the
module keyword creates a new constant that refers to the module and constants begin with a capital letter.

Q: How would you check if a module has been included by an object?
A: Using
#is_a? such as with my_obj.is_a? MyModule.

Q: What does
Module#module_function do?
A: Makes class copies of the specified methods and makes instance methods private.
Structs
Q: What is a Struct in Ruby?
A: A core Ruby class that generates other classes containing accessor methods for the specified fields.

Q: Can methods be added to a
Struct?
A: Yes.
Inheritance
Q: What's the difference between Object#is_a? and Object#instance_of??
A:
Object#instance_of? ignores inheritance and any mixed-in modules.

Q: If the
super keyword is used in a method without any arguments, which if any arguments get passed to the superclass method?
A: All arguments that were passed to the current subclass method will be passed to the superclass method.

Q: Are singleton methods inherited?
A: No, since they are not defined by a class and thus are unrelated to the inheritance mechanism.

Q: Are class methods inherited?
A: Yes.

Q: Are constants inherited?
A: Yes.

Q: Are class variables inherited?
A: No. The behavior is different than inheritance. Any alteration of a class variable by a subclass affects that class variable in the superclass and all other subclasses of the superclass.

Q: Why might you want to avoid the use of class variables?
A: Their values can be changed at any point in the inheritance chain which can cause unexpected behavior in parent classes or subclasses which use those class variables.

Q: What should you watch out for when subclassing a class that is unknown to you?
A: Overriding private methods or overwriting class variables.

Q: How might you prevent a method on a superclass from being inherited by a subclass?
A: Override the method in the subclass or
undef the method in the subclass.
Metaprogramming
Q: Can Module#attr_reader be considered an example of metaprogramming?
A: Yes, since it creates getter methods at the time of the enclosing class definition.

Q: How might you access an instance variable of a receiver object from outside the scope of the receiver object?
A: With an accessor method or using
Object#instance_variable_get, BasicObject#instance_eval, or Binding#eval.

Q: Which method is invoked when a method is not found?
A: The nearest
#method_missing

Q: How can you open an eigenclass from within its associated class?
A:
class << self

Q: What is a binding?
A: A representation of an object's variable bindings at some moment.

Q: What is Ruby's reflection API?
A: A collection of methods mostly defined by
Kernel, Object, and Module that allow a program to examine its own state and structure.

Q: Which method is invoked when a constant is not found?
A: The nearest
#const_missing

Q:
Module#define_method accepts how many and of what types of arguments?
A: A symbol as the method name and either a block or a
Method object as the method body.

Q: Can
#eval accept a block?
A: No,
#eval accepts a string. However, Module#class_eval and BasicObject#instance_eval can accept blocks.

Q: How might you obtain a reference to an eigenclass from within its associated class?
A:
Object#singleton_class, eigenclass = class << self; self; end

Q: How might you alter method visibility from outside a class definition?
A: Using
Module#class_eval

Q: What is the difference between
BasicObject#instance_eval and BasicObject#instance_exec?
A:
BasicObject#instance_exec can only accept a block, not a string, and it can accept arguments and pass them to the block, allowing the block to be evaluated in the context of the receiver object with parameters whose values come from the block.

Q: Where do
#class_variable_get and #class_variable_set live in the object model?
A:
Module

Q: Where do
#instance_variable_get and #instance_variable_set live in the object model?
A:
Object

Q: Where do
#local_variables and #global_variables live in the object model?
A:
Kernel
Loading Modules, Files, and Gems
Loading
Q: What is $LOAD_PATH?
A: A global array of strings of the directories to be searched when loading files with the load and require methods.
$LOAD_PATH is equivalent to $:.

Q: What is the difference between
Kernel#require and Kernel#load?
A:
Kernel#require can load binary extensions. Kernel#require does not require a filename extension. Kernel#require prevents multiple loads of the same file path. Kernel#load loads the specified file at the current $SAFE level while Kernel#require loads the specified file with a $SAFE level of 0.

Q: Does a file loaded with
Kernel#require or Kernel#load have access to the local variables of the referencing file?
A: No.

Q: What is the difference between
Kernel#require and Kernel#require_relative?
A:
Kernel#require_relative ignores the load path.

Q: What does
Kernel#autoload do?
A: Allows lazy-loading of files when a constant assigned to a file is first referenced.
Files
Q: What does File::expand_path do?
A: Converts a relative path to a fully qualified path.

Q: What method(s) in class
Dir can be used to list the contents of a directory?
A:
Dir::entries, Dir::foreach, Dir#each...

Q: What is an
IO object?
A: An IO object is an instance of class
IO that can be used for reading or writing binary data to and from a file.
Gems
Q: Are RubyGems installation directories included in $LOAD_PATH?
A: Yes.

Q: If more than one version of a Gem is installed, which version will be used?
A: The Gem with the highest version number.
Security
Q: What can you say about objects derived from tainted objects?
A: They will also be tainted.

Q: What is the default
$SAFE level?
A: 0

Q: What happens when you attempt to lower the
$SAFE level?
A: The
$SAFE level cannot be lowered; it can only be raised.

Q: What is the difference between taint and trust?
A: Taint is derived from the environment such as the command line, environment variables, files, sockets, etc..., while trust is derived from the
$SAFE level of the originating code. Untrusted objects are both untrusted and tainted.
Exceptions
Q: What error is raised if a method is passed the wrong number of arguments?
A:
ArgumentError

Q: What error is raised if method name resolution fails?
A:
NoMethodError

Q: The superclass of
StandardError is __.
A:
Exception

Q: What does the default implementation of
BasicObject#method_missing do?
A: Raises a
NoMethodError.

Q: What happens if you attempt to redefine
BasicObject#__send__?
A: Ruby issues a warning.
Debugging
Q: What is the difference between #to_s and #inspect?
A:
#inspect is the same as #to_s, except some classes redefine #inspect to provide output that is more helpful for debugging.

Q: What is the difference between
#puts and #p?
A:
#p converts objects to strings with an #inspect method instead of with a #to_s method.

Q: Which Ruby interpreter option enables debugging?
A:
-d / --debug

Q: What is the global variable for the last exception raised?
A:
$ERROR_INFO equivalent to $!

Q: How can you obtain the current state of the call stack?
A: Using
Exception#backtrace or Kernel#caller

Q: What does
Kernel#__method__ return?
A: The name of the currently executing method as a symbol.

Q: What is the synonym of
Kernel#__method__?
A:
Kernel#__callee__
The Ruby Environment and the Interpreter
Q: What is the difference between #puts and #print?
A:
#puts appends a newline character to the output.

Q: Which Ruby interpreter option allows running of one-line scripts?
A:
-e

Q: Where do the curly brackets to define a hash literal
{} exist in the object model?
A: It does not exist within the object model - it is a function of the interpreter.

Q: What is the default encoding in MRI?
A: UTF-8

Q: How does Ruby know that a setter method such as
X#[]= should be called in the expression x.field = []?
A: It is a syntactical conversion in the interpreter.

Q: What is the global constant to access arguments specified on the command line?
A:
ARGV

Q: Which Ruby interpreter option enables warnings about deprecated or problematic code?
A:
-w

Q: In MRI, which objects are not subject to garbage collection?
A: Symbols.

Q: What module in the standard library enables English language alternatives to terse global variables?
A:
English


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
oriented.
Here are some of the other characteristices of the Agile
methodology.
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 this: Request first comes to the controller, controller finds and appropriate view, your view interacts with model, model interacts with your database, 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.
Callbacks
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] = “puneet” 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.
form_for
——-
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
form_tag:
—–
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.
Example:
<% 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

Performance
Threads/Fibers
Encoding/Unicode
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.
Reference:
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|
MyClass.send(method)
end
How to create a method dynamically
A.class Message
[:hello, :goodbye].each do |method_name|
define_method method_name do |arg|
“#{method_name} #{arg}”
end
end
end
#irb
Message.instance_methods false #=> [:hello, :goodbye]
Message.new.hello ‘emre’ #=> “hello emre”
Message.new.goodbye ‘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.
Reference
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.
Reference:
http://apidock.com/rails/ActiveRecord/Observer
What is rails sweeper
A:http://dev.mensfeld.pl/2011/07/using-rails-sweepers-outside-controllers/
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 -%>
Hi
<% end -%>
It’ll produce:
Hi
and not this:
Hi
Difference between render and 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.
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
A. Refer http://stuff.lilleaas.net/active_record_anywhere
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. http://magicmodels.rubyforge.org/magic_multi_connections/, 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 :
http://magicmodels.rubyforge.org/magic_multi_connections/
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’
end
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.
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}
end
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?
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))
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.
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.
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.”
More Questions and Answers of this will be published very soon :)
1. What is Rails?

1. Rails is a extremely productive web-application framework written in Ruby language by David Hansson.

2. Rails are an open source Ruby framework for developing database-backend web applications.

3. Rails include everything needed to create a database-driven web application using the Model-View-Controller (MVC) pattern.

2. What are the various components of Rail?

1. Action Pack: Action Pack is a single gem that contains Action Controller, Action View and Action Dispatch. The “VC” part of “MVC”.

Action Controller: Action Controller is the component that manages the controllers in a Rails application. The Action Controller framework processes incoming requests to a Rails application, extracts parameters, and dispatches them to the intended action.

Services provided by Action Controller include session management, template rendering, and redirect management.

Action View:  Action View manages the views of your Rails application. It can create both HTML and XML output by default.

Action View manages rendering templates, including nested and partial templates, and includes built-in AJAX support.

Action Dispatch: Action Dispatch handles routing of web requests and dispatches them as you want, either to your application or any other Rack application. Rack applications are a more advanced topic and are covered in a separate guide called Rails on Rack.

2. Action Mailer: Action Mailer is a framework for building e-mail services. You can use Action Mailer to receive and process incoming email and send simple plain text or complex multipart emails based on flexible templates.

3. Active Model: Active Model provides a defined interface between the Action Pack gem services and Object Relationship Mapping gems such as Active Record. Active Model allows Rails to utilize other ORM frameworks in place of Active Record if your application needs this.

4. Active Record: Active Record are like Object Relational Mapping (ORM), where classes are mapped to table, objects are mapped to columns and object attributes are mapped to data in the table.

5. Active Resource: Active Resource provides a framework for managing the connection between business objects and RESTful web services. It implements a way to map web-based resources to local objects with CRUD semantics.

6. Active Support: Active Support is an extensive collection of utility classes and standard Ruby library extensions that are used in Rails, both by the core code and by your applications.

3. Explain about RESTful Architecture.

RESTful: REST stands for Representational State Transfer. REST is an architecture for designing both web applications and application programming interfaces (API’s), that’s uses HTTP.

RESTful interface means clean URLs, less code, CRUD interface. CRUD means Create-READ-UPDATE-DESTROY. In REST, they add 2 new verbs, i.e, PUT, DELETE.

4. Why Ruby on Rails?

There are lot of advantages of using ruby on rails.

1. 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”

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

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

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

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

6. Metaprogramming: Metaprogramming techniques use programs to write programs.

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

8. Rest Support.

9. Action Mailer

5. What do you mean by render and redirect_to?

render causes rails to generate a response whose content is provided by rendering one of your templates. Means, it will direct goes to view page.

redirect_to generates a response that, instead of delivering content to the browser, just tells it to request another url. Means it first checks actions in controller and then goes to view page.

6. What is ORM in Rails?

ORM tends for Object-Relationship-Model, where Classes are mapped to table in the database, and Objects are directly mapped to the rows in the table.

7. How many Types of Associations Relationships does a Model have?

When you have more than one model in your rails application, you would need to create connection between those models. You can do this via associations. Active Record supports three types of associations:

one-to-one: A one-to-one relationship exists when one item has exactly one of another item. For example, a person has exactly one birthday or a dog has exactly one owner.

one-to-many: A one-to-many relationship exists when a single object can be a member of many other objects. For instance, one subject can have many books.

many-to-many: A many-to-many relationship exists when the first object is related to one or more of a second object, and the second object is related to one or many of the first object.

You indicate these associations by adding declarations to your models: has_one, has_many, belongs_to, and has_and_belongs_to_many.

8. What are helpers and how to use helpers in ROR?

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.

9. 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 ApplicationController, it will be run on every controller in your application.

10. What is MVC? and how it Works?

MVC tends for Model-View-Controller, used by many languages like PHP, Perl, Python etc. The flow goes 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.

11. What is Session and Cookies?

Session is used to store user information on the server side. Maximum size is 4 kb. Cookies are used to store information on the browser side or we can say client side.

12. What is request.xhr?

A request.xhr tells the controller that the new Ajax request has come, It always return Boolean values (TRUE or FALSE)

13. What things we can define in the model?

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
6. Active record Associations Relationship

14.  How many types of callbacks available in ROR?

 (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

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

16. How to use two databases into a single application?

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”
 
17. What are the various changes between the Rails Version 2 and 3?

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. HTML5 support

18. What is TDD and BDD?

TDD stands for Test-Driven-Development and BDD stands for Behavior-Driven-Development.

19. What are the servers supported by ruby on rails?

RoR was generally preferred over WEBrick server at the time of writing, but it can also be run by:
Lighttpd (pronounced ‘lighty’) is an open-source web server more optimized for speed-critical environments.
Abyss Web Server- is a compact web server available for windows, Mac osX and Linux operating system.
Apache and nginx

20. What do you mean by 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.

21. What is the log that has to seen to check for an error in ruby rails?

Rails will report errors from Apache in log/apache.log and errors from the ruby code in log/development.log. If you having a problem, do have a look at what these log are saying.

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

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. GET and POST Method?

GET is basically for just getting (retrieving) data, whereas POST may involve anything, like storing or updating data, or ordering a product, or sending E-mail.


Comments

  1. BlueHost is one of the best web-hosting company with plans for any hosting requirements.

    ReplyDelete
  2. "Great blog created by you. I read your blog, its best and useful information. You have done a great work. Super blogging and keep it up.php jobs in hyderabad.
    "

    ReplyDelete

Post a Comment

Popular posts from this blog

Gem::LoadError (Specified 'mysql2' for database adapter, but the gem is not loaded. Add `gem 'mysql2'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord).?

Gem::LoadError (Specified 'mysql2' for database adapter, but the gem is not loaded. Add `gem 'mysql2'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord).) In rails?


1)change the gemfile in mysql version
 gem 'mysql2'

2)Change to mysql2 version
 gem 'mysql2','0.3.20'

Get user accessing ip address in rails?

Get user accessing ip address rails?

request.ip ->returns the ip, whether is is a local proxy ip (localhost address) or not.
*request.remote_ip -> is smarter and gets the ip address of the client outside of local proxies.
3)If you are using apache in front of a mongrel, then remote_ip will return the source address of the request, which in this case will be local host because the Apache web server is making the request, so instead put this in your controller:

@remote_ip = request.env["HTTP_X_FORWARDED_FOR"]

PayUMoney Integration in Ruby on Rails

PayUMoney Integration in Ruby on Rails


Generating Cheksum in Payu
   Hash or Checksum
= sha512(key|txnid|amount|productinfo|firstname|email|u
df1|udf2|udf3|udf4|udf5||||||salt)



Controller Code Will be
def payumoney
  @key = "gtKFFx"
  @salt =  "eCwWELxi"
  val = "#{key|txnid|amount|productinfo|firstname|email|u
df1|udf2|udf3|udf4|udf5||||||#{@salt}"
 @checksum = Digest::SHA512.hexdigest("#{val}")
end

<form action="https://test.payu.in/_payment" method='post' id='sub'  >
    <input type="hidden" name="key" value="<%=@key%>">
    <input type="hidden" name="hash" value="<%=@checksum%>">
    <input type="hidden" name="txnid" value="TXN1234">
    <input type="hidden" name="amount" value="200">
    <input type="hidden" name="firstname" value=&quo…