Dear Readers, Welcome to Ruby on Rails Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your Job interview for the subject of Ruby on Rails. These Ruby on Rails Questions are very important for campus placement test and job interviews. As per my experience good interviewers hardly plan to ask any particular questions during your Job interview and these model questions are asked in the online technical test and interview of many Medical Industry.
There are lot of advantages of using ruby on rails:
1. DRY Principal
2. Convention over Configuration
3. Gems and Plugins
4. Scaffolding
5. Pure OOP Concept
6. Rest Support
7. Rack support
8. Action Mailer
9. Rpc support
10. Rexml Support
11. etc..
Ruby is the brain child of a Japanese programmer Matz. He created Ruby. It is a cross platform object oriented language. It helps you in knowing what your code does in your application. With legacy code it gives you the power of administration and organization tasks. Being open source, it did go into great lengths of development.
Classes, variables, methods, constants and modules can be referred by ruby names. When you want to distinguish between various names you can specify that by the first character of the name. Some of the names are used as reserve words which should not be used for any other purpose. A name can be lowercase letter, upper case letter, number, or an underscore, make sure that you follow the name by name characters.
Symbol are same like string but both behaviors is different based on object_id, memory and process time (cpu time) Strings are mutable , Symbols are immutable.
Mutable objects can be changed after assignment while immutable objects can only be overwritten.
For example
p "string object jak".object_id #=> 22956070
p "string object jak".object_id #=> 22956030
p "string object jak".object_id #=> 22956090
p :symbol_object_jak.object_id #=> 247378
p :symbol_object_jak.object_id #=> 247378
p :symbol_object_jak.object_id #=> 247378
p " string object jak ".to_sym.object_id #=> 247518
p " string object jak ".to_sym.object_id #=> 247518
p " string object jak ".to_sym.object_id #=> 247518
p :symbol_object_jak.to_s.object_id #=> 22704460
p :symbol_object_jak.to_s.object_id #=> 22687010
p :symbol_object_jak.to_s.object_id #=> 21141310
And also it will differ by process time
For example:
Testing two symbol values for equality (or non-equality) is faster than testing two string values for equality,
Note : Each unique string value has an associated symbol
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] = “arunkumar” it remains when the browser is not closed
A request.xhr tells the controller that the new Ajax request has come, It always return Boolean values (TRUE or FALSE)
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, for Example your url is something like this:
http://localhost:3000/users/new
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.
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
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.
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 secondobject, 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.
render example:
render :partial
render :new
It will render the template new.rhtml without calling or redirecting to the new action.
redirect example:
redirect_to :controller => ‘users’, :action => ‘new’
It forces the clients browser to request the new action.
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.
You can run application by uncomment the line in environment.rb
Path => rootpath conf/ environment.rb
# Skip frameworks you're not going to use (only works if using vendor/rails)
config.frameworks -= [ :action_web_service, :action_mailer,:active_record ]
You can use ActiveRecord anywhere!
require 'rubygems'
require 'active_record'
ActiveRecord::Base.establish_connection({
:adapter => 'postgresql',
:user => 'foo',
:password => 'bar',
:database => 'whatever'
})
class Task <>
set_table_tame "a_legacy_thingie"
def utility_methods
update_attribute(:title, "yep")
end
end
Task.find(:first)
Etcetera. It’s ActiveRecord, you know what to do. Going wild:
ActiveRecord::Base.establish_connection(:adapter => "sqlite3",
:dbfile => ":memory:")
ActiveRecord::Schema.define(:version => 1) do
create_table :posts do |t|
t.string :title
t.text :excerpt, :body
end
end
class Post <>
validates_presence_of :title
end
Post.create(:title => "A new post!")
Post.create(:title => "Another post",
:excerpt => "The excerpt is an excerpt.")
puts Post.count
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 theprogramming 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.
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
Ruby Supports only Single Inheritance.
You can achieve Multiple Inheritance through MIXIN concept means you achieve using module by including it with classes.
• (-) 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
• create_table(name, options)
• drop_table(name)
• rename_table(old_name, new_name)
• add_column(table_name, column_name, type, options)
• rename_column(table_name, column_name, new_column_name)
• change_column(table_name, column_name, type, options)
• remove_column(table_name, column_name)
• add_index(table_name, column_name, index_type)
• remove_index(table_name, column_name)
Migrations support all the basic data types: string, text, integer, float, datetime, timestamp, time, date, binary and boolean:
• string - is for small data types such as a title.
• text - is for longer pieces of textual data, such as the description.
• integer - is for whole numbers.
• float - is for decimals.
• datetime and timestamp - store the date and time into a column.
• date and time - store either the date only or time only.
• binary - is for storing data such as images, audio, or movies.
• boolean - is for storing true or false values.
Valid column options are:
• limit ( :limit => “50” )
• default (:default => “blah” )
• null (:null => false implies NOT NULL)
Methods that return a boolean result are typically named with a ending question mark. For example: def active? return true #just always returning true end
The strip! method modifies the variable directly. Calling strip (without the !) returns a copy of the variable with the modifications, the original variable is not
altered.
@name is an instance variable and @@name is a class variable
Rails will report errors from Apache in log/apache.log and errors from the Ruby code in log/development.log. If you're having a problem, do have a look at what these logs are saying. On Unix and Mac OS X you may run tail -f log/development.log in a separate terminal to monitor your application's execution.
A class variable starts with an @@ sign which is immediately followed by upper or lower case letter. You can also put some name characters after the letters which stand to be a pure optional. A class variable can be shared among all the objects of a class. A single copy of a class variable exists for each and every given class.
To write a global variable you start the variable with a $ sign which should be followed by a name character. Ruby defines a number of global variables which also include other punctuation characters such as $_ and $-k.
For example: If you declare one variable as global we can access any where, where as class variable visibility only in the class Example
class Test
def h
 $a = 5
 @b = 4
Â
while $a > 0
puts $a
$a= $a - 1
end
end
end
test = Test.new
test.h
puts $a # 5
puts @b #nil
The main Symbol let the start_tabnav method know to look for a special MainTabnav class where all the magic happens
There are several packages that you can download and install. The prebuilt Rails installer called Install rail which currently is only for Windows
Rails will report errors from Apache in log/apache.log and errors from the Ruby code in log/development.log. If you're having a problem, do have a look at what these logs are saying. On Unix and Mac OS X you may run tail -f log/development.log in a separate terminal to monitor your application's execution.
Ruby uses the super keyword to call the superclass implementation of the current method
False is a boolean datatype, Nil is not a data type it have object_id 4
A:def self.methodname
--------
--------
end
or
def classname.methodname
--------
--------
end
class jak
def method1
--------
--------
end
end
obj=jak.new
It is single object
def obj.object_method_one
--------
--------
end
obj.Send(object_method_every)
It will be created every for every object creation
Something that’s used in an expression to manipulate objects such as + (plus), - (minus), * (multiply), and / (divide). You can also use operators to do
comparisons,such as with <, >, and &&.
for..in
untill..end
while..end
do..end
Note: You can also use each to iterate a array as loop not exactly like loop
Classes,Objects,Inheritance,Singleton methods,polymorphism(accomplished by over riding and overloading) are some oo concepts supported by ruby.
A new scope for a local variable is introduced in the toplevel, a class (module) definition, a method defintion. In a procedure block a new scope is introduced but you can access to a local variable outside the block.
The scope in a block is special because a local variable should be localized in Thread and Proc objects.
Iterator is handled using keyword 'each' in ruby.
For example
number=[1,2,3]
then we can use iterator as
number.each do |i|
puts i
end
Above prints the values of an array $no which is accomplished using iterator.
By applying the access modifier : Public , Private and Protected acces Modifier
A method that loads and processes the Ruby code from a separate file, including whatever classes, modules, methods, and constants are in that file into the current scope. load is similar, but rather than performing the inclusion operation once, it reprocesses the code every time load is called.
Ruby has a strong set of class libraries and it covers from a variety of domains such as thread programming, domains and data types. Also ruby is a new language and it also has additional libraries coming every day. Many of the new languages which do exist have huge libraries because of their age.
Ruby language can be ported to many platforms. Ruby programs can be ported to many platforms without any modification to the source code. This feature made the language very useful and highly used by many programmers worldwide. Some of the platforms used are DOS, UNIX, WINDOWS, etc.
Ruby is an object oriented language and every object oriented language tends to allocate many objects during execution of the program. Ruby deletes unallocated and unused objects automatically. This feature can be controlled by applying proper syntax and program through ruby.
Ruby`s language is executed from the command line like most of the scripting languages. Programming and behavior language environment can be controlled from the interpreter itself. Some of the commands which are used are as follows –d, -h, -e prog, -v, -T, -r lib, etc.
Following are some of the environment variables used to control the behavior programming of ruby. While programming ENV object lists some of the current variables.
RUBYLIB path searches for libraries. Make sure that you separate each path with colons. RUBYOPT passes command line options to Ruby interpreter. There are many more which can be obtained by searching the huge pool of library.
Define operator defines whether a passed expression is defined or not. If the expression is defined it returns the description string or null if the expression is not
defined. If a variable is defined it gets initialized. If method call is defined as true then method also gets defined. This is also the same case with super and
yield.
Methods in ruby basically perform two functions, named operation and the code present in the class which does a specific function. In Ruby all your algorithms live in methods which in turn is present on objects. Ruby does not have any provision for functions. Code present in Ruby is always a method of some object. Behind the scenes ruby gives you the flexibility to work with methods as functions if you are considering working with other languages.
This function calls a method and it can take any number of arguments and expr. Make sure that you put an asterisk or an ampersand before the expression. Last expr argument can be declared with a hash without any braces. If you want to increase the size of the array value then make sure that you put an asterisk before expression.
“::” can be used to separate the class from methods.
Unlike other programming languages ruby deals with extremely large numbers it doesn’t have any barriers. There is no limit on the extent of limit of number usage. Ruby performs this function with two different classes they are fixnum and bignum. Fixnum represents easily managed small numbers and bignum represents big numbers. Ruby entirely handles the functioning of these two classes which leaves a programmer to concentrate on his arithmetic operations.
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.
Interpolation is a very important process in Ruby. Interpolation is the process of inserting a string into a literal. There is only one way in which you can
interpolate a string into a literal by placing a Hash (#) within {} open and close brackets. This refers to a new name to by referring to the copy of the original
method.
Ruby code blocks form an important part of ruby and are very fun to use. With the help of this feature you can place your code between do-end and you can associate them with method invocations and you can get an impression that they are like parameters. They may appear near to a source of the code and adjacent to a method call.
The code is not executed during the program execution but it is executed when the context of its appearance is met or when it enters a method.