Last Updated: February 25, 2016
·
2.108K
· Rohit Trivedi

Ruby on Rails Interview questions

toptal RoR interview post

http://www.sitepoint.com/look-ruby-2-1/

http://www.toptal.com/ruby-on-rails/interview-questions

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

codequizzes

What is new in Ruby 2.0 ?

Keyword arguments

def wrap(string, before: "<", after: ">")
  "#{before}#{string}#{after}" # no need to retrieve options from a hash
end

# optional
wrap("foo")                                  #=> "<foo>"
# one or the other
wrap("foo", before: "#<")                    #=> "#<foo>"
wrap("foo", after: "]")                      #=> "<foo]"
# order not important
wrap("foo", after: "]", before: "[")         #=> "[foo]"

%i and %I symbol array literal

%i{an array of symbols}   #=> [:an, :array, :of, :symbols]

%I{#{1 + 1}x #{2 + 2}x}   #=> [:"2x", :"4x"]

Refinements

You create a refinement to a class, name spaced inside a module

module NumberQuery
  refine String do
    def number?
      match(/\A[1-9][0-9]*\z/) ? true : false
    end
  end
end

#this refinement isn’t visible by default
"123".respond_to?(:number?)   #=> false

#once you declare that you are using the module with the refinement, then it becomes visible.

using NumberQuery
"123".number?                 #=> true

Module#prepend

Module gains #prepend as a compliment to #include, it works just like include, but it inserts the module in to the inheritance chain as if it were a subclass rather than a superclass.

Object
superclass
included module
class
prepended module
class Foo
  def do_stuff
    puts "doing stuff"
  end
end

module Wrapper
  def do_stuff
    puts "before stuff"
    super
    puts "after stuff"
  end
end

class Foo
  prepend Wrapper
end

Foo.new.do_stuff

#output
before stuff
doing stuff
after stuff

Others

Unbound methods from a module can be bound to any object

const_get understands namespaces

to_h as standard for ‘convert to hash’
Array#bsearch and Range#bsearch

Rubygems Gemfile support
ruby gem install --file Gemfile

Like install, this only uses the Gemfile, ignoring Gemfile.lock, so it’s less strict than Bundler. It also only activates the specified versions, you’ll still need to require the gems in your code.

Use warn like puts

Garbage collection improvements

OpenStruct can act like a hash

Fine more here :
Link


What is new in Ruby 2.1 ?

Rational Number and Complex Number Literals

def‘s Return Value

Refinements are no longer experimental in Ruby 2.1

Required Keyword Arguments

Exception#cause

Find more here: Link

Is everything is object in ruby ?

Depends on what you mean by "everything". Fixnums are, as the others have demonstrated. Classes also are, as instances of class Class.

Methods, operators and blocks aren't, but can be wrapped by objects (Proc). Simple assignment is not, and can't. Statements like while also aren't and can't. Comments obviously also fall in the latter group.

What is difference between string and symbol in ruby ?

symbols are immutable

puts "hello" << " world"
puts :hello << :" world"

# => hello world
# => *.rb:4: undefined method `<<' for :hello:Symbol (NoMethodError)

strings can be made immutable using freeze method

strings are stored in memory while symbols are stored in symbol table. Thus symbols are more efficient for garbage collection and

Ruby’s garbage collector, or GC, is of the mark and sweep variety. This means that objects to be destroyed are marked during the programs operation. The GC then sweeps up all the marked objects on the heap whenever it has some spare time. However, above we are creating a new object, storing and ultimately destroying it when reusing the same object would be much more efficient.

Find more here : Link


What is difference between a Block, a Proc and a Lambda ?

all of these are closures in ruby

# Block Examples

[1,2,3].each { |x| puts x*2 }   # block is in between the curly braces

[1,2,3].each do |x|
  puts x*2                    # block is everything between the do and end
end

# Proc Examples             
p = Proc.new { |x| puts x*2 }
[1,2,3].each(&p)              # The '&' tells ruby to turn the proc into a block 

proc = Proc.new { puts "Hello World" }
proc.call                     # The body of the Proc object gets executed when called

# Lambda Examples            
lam = lambda { |x| puts x*2 }
[1,2,3].each(&lam)

lam = lambda { puts "Hello World" }
lam.call

differenced:

Procs are objects, blocks are not

At most one block can appear in an argument list but multiple Procs can be passed as arguments to a method

procs and lambdas are both Proc objects.

Lambda is a flavour of Proc

proc   # returns '#<Proc:0x007f96b1032d30@(irb):75>'
lam    # returns '<Proc:0x007f96b1b41938@(irb):76 (lambda)>'

Lambdas check the number of arguments, while procs do not

```ruby
lam = lambda { |x| puts x }    # creates a lambda that takes 1 argument
lam.call(2)                    # prints out 2
lam.call                       # ArgumentError: wrong number of arguments (0 for 1)
lam.call(1,2,3)                # ArgumentError: wrong number of arguments (3 for 1)

proc = Proc.new { |x| puts x } # creates a proc that takes 1 argument
proc.call(2)                   # prints out 2
proc.call                      # returns nil
proc.call(1,2,3)               # prints out 1 and forgets about the extra arguments

Lambdas and procs treat the ‘return’ keyword differently

‘return’ inside of a lambda triggers the code right outside of the lambda code

def lambda_test
  lam = lambda { return }
  lam.call
  puts "Hello world"
end

lambda_test                 # calling lambda_test prints 'Hello World'

‘return’ inside of a proc triggers the code outside of the method where the proc is being executed

def proc_test
  proc = Proc.new { return }
  proc.call
  puts "Hello world"
end

proc_test                 # calling proc_test prints nothing

Find more here : Link


difference between load, require, include and extend in ruby ?

http://ionrails.com/2009/09/19/ruby_require-vs-load-vs-include-vs-extend/


What is Ruby Object Model ?

Every class is a object of class model
so
superclass method give the parent class

class A
end

class B < A
end

B.class => Class
A.class => Class
B.superclass => A
Class.class => Class
Class.superclass => Module
Module.class => Class
Module.superclass => Object
Object.class => Class
Object.superclass => BasicObject
BasicObject.class => Class
BasicObject.superclass => nil
Kernel.class -> Module

More details here : Link(http://skilldrick.co.uk/2011/08/understanding-the-ruby-object-model/)


Explain singleton classes in ruby

Read in details here : Link


What is the difference between Class and Module in ruby ?

<table>
<tr>
<th>
<th>class</th>
<th>module</th>
</tr>
<tr>
<td>instantiation</td>
<td>can be instantiated</td>
<td>can not be instantiated</td>
</tr>
<tr>
<td>usage</td>
<td>object creation</td>
<td>mixin facility. provide a namespace.</td>
</tr>
<tr>
<td>superclass</td>
<td>module</td>
<td>object</td>
</tr>
<tr>
<td>consists of</td>
<td>methods, constants, and variables</td>
<td>methods, constants, and classes</td>
</tr>
<tr>
<td>methods</td>
<td>class methods, instance methods</td>
<td>module methods, instance methods</td>
</tr>
<tr>
<td>inheritance</td>
<td>inherits behaviors and can be base for inheritance</td>
<td>No inheritance</td>
</tr>
<tr>
<td>inclusion</td>
<td>cannot be included</td>
<td>can be included in classes and modules</td>
</tr>
</table>

From here : Link

What is difference between class variable and class instance variable

classvariable : @@carname

will be same for child classes

any changes in this will reflect in all other sibling classes or parent class

class Polygon
  @@sides = 10
  def self.sides
    @@sides
  end
end

puts Polygon.sides # => 10

class Triangle < Polygon
  @@sides = 3
end

puts Triangle.sides # => 3
puts Polygon.sides # => 3

class Rectangle < Polygon
  @@sides = 4
end

puts Polygon.sides # => 4

class instance variables :

What is a class? It’s an object. What can objects have? Objects can have class and instance variables. This means that a class can have instance variables.

class Polygon
  @sides = 10
end

puts Polygon.class_variables # => @@sides
puts Polygon.instance_variables # => @sides

class Polygon
  attr_accessor :sides
  @sides = 10
end

puts Polygon.sides # => NoMethodError: undefined method ‘sides’ for Polygon:Class

class Polygon
  class << self; attr_accessor :sides end
  @sides = 8
end

puts Polygon.sides # => 8

class Triangle < Polygon
  @sides = 3
end

puts Triangle.sides # => 3
puts Polygon.sides # => 8

class Octogon < Polygon; end
puts Octogon.sides # => nil

Read more from here ; Link

More Question:

Explain method lookup in ruby .

Read more here : Link

Explain classeval/instanceeval .

http://web.stanford.edu/class/cs142/cgi-bin/classEval.php

classeval => it defines instance method for class
instance
eval => it defines class methods for singleton class of an object. So it apply specifically only to the object for which it is defined

Read more here : Link

Explain definemethod/definesingleton_method and method missing in rails

define_method => for creating instance methods in class

definesingletonmethod => for creating class methods

method_missing => to define methods when method is created with combiantions of words and those combinations are not known.

eg. findbyemailandname, findby* etc

Read more here : Link


Explain include , included, extend, extended, prepend, prepended


Rails Related Questions

difference between Arel and ActiveRecord


Web Development related questions


http protocol?


how application server known about dynamic template?


What is Restful ?


explain HTTP protocol .


what is difference between session and cookies ?