Thursday, February 7, 2013

Rails interview Docs


1.1 What is Ruby?

Ruby is a pure object-oriented programming language with a super clean syntax that makes programming elegant and fun. Ruby successfully combines Smalltalk’s conceptual elegance, Python’s ease of use and learning, and Perl’s pragmatism. Ruby originated in Japan in the early 1990s, and has started to become popular worldwide in the past few years as more English language books and documentation have become available.



1.2 What is Rails?

Rails is an open source Ruby framework for developing database-backed web applications. What’s special about that? There are dozens of frameworks out there and most of them have been around much longer than Rails. Why should you care about yet another framework? What would you think if I told you that you could develop a web application at least ten times faster with Rails than you could with a typical Java framework? You can–without making any sacrifices in the quality of your application! How is this possible? Part of the answer is in the Ruby programming language. Many things that are very simple to do in Ruby are not even possible in most other languages. Rails takes full advantage of this. The rest of the answer is in two of Rail’s guiding principles: less software and convention over configuration. Less software means you write fewer lines of code to implement your application. Keeping your code small means faster development and fewer bugs, which makes your code easier to understand, maintain, and enhance. Very shortly, you will see how Rails cuts your code burden. Convention over configuration means an end to verbose XML configuration files–there aren’t any in Rails! Instead of configuration files, a Rails application uses a few simple programming conventions that allow it to figure out everything through reflection and discovery. Your application code and your running database already contain everything that Rails needs to know!



1.3 How to capitalize UTF8 string without downcasing

What is the best way to capitalize the first character of a UTF8 string? String#capitalize downcases the rest of the string which is unacceptable since there can be capitals in the middle of the string. (“see New York”.capitalize => “See new york”). Just picking off the first byte and capitalizing that is also not an option since the first character can be a multibyte UTF-8 character. The only thing I can think of so far is either using Ruby 1.9 or the the Rails multibyte Chars library to split off the first character and then capitalize that and join it back together. Surely there must be a better way for such a common problem?


1.4 What is the naming conventions for methods that return a boolean result?

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


1.5 What are the object-oriented programming features supported by Ruby?

Classes,Objects,Inheritance,Singleton methods,polymorphism(accomplished by over riding and overloading) are some oo concepts supported by ruby. …


1.6 What are the operating systems supported by Ruby?

Windows and linux operating systems are supported by the Ruby


1.7 Whats the difference between symbol and string?

Symbol refers to the same memory location where string generates a new id every time for eg.
STRING
irb(main):019:0> “ruby”.object_id
=> 24095860
irb(main):020:0> “ruby”.object_id
=> 24092310
irb(main):021:0> “ruby”.object_id
=> 24088760
irb(main):022:0>
SYMBOL
irb(main):022:0> :ruby.object_id
=> 102978
irb(main):023:0> :ruby.object_id
=> 102978
irb(main):024:0> :ruby.object_id
=> 102978
irb(main):025:0> :ruby.object_id
=> 102978
irb(main):026:0>


1.8 How do you comment out a block of code?

Use =begin and =end. =begin def
my_commented_out_method end =end
You could use successive # signs, but that’s just tedious: # # def my commented_out_method # end #


1.9 How would you create a new ruby rail application?

To create a new ruby rail application rails my_app cd my_app


1.10 What is the difference between nil and false in ruby?

False is a boolean datatype Nil is not a data type


1.11 What two delimiters are used for blocks?

Curly braces {…} and “do”…”end” Bonus: coding convention is to use curly braces if the code will fit on one line and “do”…”end” syntax if the block contains multiple lines.


1.12 What is the naming conventions for methods that return a boolean result?

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


1.13 Explain about the programming language ruby?

Ruby is the interpreted scripting language for quick and easy object-oriented programming. It has many features to process text files and to do system management tasks (as in Perl). It is simple, straight-forward, extensible, and portable. Oh, I need to mention, it’s totally free, which means not only free of charge, but also freedom to use, copy, modify, and distribute it.

Features of Ruby
* Ruby has simple syntax, partially inspired by Eiffel and Ada.
* Ruby has exception handling features, like Java or Python, to make it easy to handle errors.
* Ruby’s operators are syntax sugar for the methods. You can redefine them easily.
* Ruby is a complete, full, pure object oriented language: OOL. This means all data in Ruby is an object, in the sense of Smalltalk: no exceptions. Example: In Ruby, the number 1 is an instance of class Fixnum.

* Ruby’s OO is carefully designed to be both complete and open for improvements. Example: Ruby has the ability to add methods to a class, or even to an instance during runtime. So, if needed, an instance of one class *can* behave differently from other instances of the same class.

* Ruby features single inheritance only, *on purpose*. But Ruby knows the concept of modules (called Categories in Objective-C). Modules are collections of methods. Every class can import a module and so gets all its methods for free. Some of us think that this is a much clearer way than multiple inheritance, which is complex, and not used very often compared with single inheritance (don’t count C++ here, as it has often no other choice due to strong type checking!).

* Ruby features true closures. Not just unnamed function, but with present variable bindings.

* Ruby features blocks in its syntax (code surrounded by ‘{‘ … ‘}’ or ‘do’ … ‘end’). These blocks can be passed to methods, or converted into closures.

* Ruby features a true mark-and-sweep garbage collector. It works with all Ruby objects. You don’t have to care about maintaining reference counts in extension libraries. This is better for your health. ;-)

* Writing C extensions in Ruby is easier than in Perl or Python, due partly to the garbage collector, and partly to the fine extension API. SWIG interface is also available.

* Integers in Ruby can (and should) be used without counting their internal representation. There *are* small integers (instances of class Fixnum) and large integers (Bignum), but you need not worry over which one is used currently. If a value is small enough, an integer is a Fixnum, otherwise it is a Bignum. Conversion occurs automatically.

* Ruby needs no variable declarations. It uses simple naming conventions to denote the scope of variables. Examples: simple ‘var’ = local variable, ‘@var’ = instance variable, ‘$var’ = global variable. So it is also not necessary to use a tiresome ‘self.’ prepended to every instance member.

* Ruby can load extension libraries dynamically if an OS allows.

* Ruby features OS independent threading. Thus, for all platforms on which Ruby runs, you also have multithreading, regardless of if the OS supports it or not, even on MS-DOS! ;-)

* Ruby is highly portable: it is developed mostly on Linux, but works on many types of UNIX, DOS, Windows 95/98/Me/NT/2000/XP, MacOS, BeOS, OS/2, etc.


1.14 Why Ruby on Rails?

1)for fast developing websites
2)convention over configuration
3)scaffolding
4)pure Object oriented concepts
5)less coding
6)easy understanding of coding
7)follows MVC architecture
8)using library and gem files


2.1 Top-Ten Reasons To Like Rails

1. It gives agility to web development.
2. developer can create web pages with neat effects, just like the cool kids do.
3. LEt developer focus on creating the application, not feeding the framework.
4. Applications stay maintainable as they grow.
5. Manager can say “Yes” to clients more often.
6. Testing is built in (and easy) so it gets used.
7. IImmediate feedback: edit the code, hit refresh, and the change is in my
browser.
8. Meta-programming means I can program at a really high level.
9. Code generators let me get started quickly.
10. No XML!


2.2 What is is Agile Web Development with Rails?

Agile development favors
• Individuals and interactions over processes and tools
• Working software over comprehensive documentation
• Customer collaboration over contract negotiation
• Responding to change over following a plan


2.3 What is a Model ?

The model is responsible for maintaining the state of the application. model
Sometimes this state is transient, lasting for just a couple of interactions
with the user. Sometimes the state is permanent, and will be stored outside
the application, often in a database.
A model is more than just data; it enforces all the business rules that apply
to that data.


2.4 What is a View?

The view is responsible for generating a user interface, normally based view
on data in the model.


2.5 What are Controllers?

Controllers orchestrate the application. Controllers receive incoming events Controllers
(normally user input), interact with the model, and display an appropriate
view to the user.


2.6 Explain the process from request to response in rails MVC?

IN Rails application, incoming requests are first sent to a router, which works out where in the application the request should be sent, and how the request itself should be parsed. Ultimately, this phase identifies a particular method (called an action in Rails parlance) somewhere in the action controller code. The action might look at data in the request itself, it might interact with the model, and it might cause other actions to be invoked. Eventually the action prepares information for the view which renders something to the user.


2.7 Object/Relational Mapping?

ORM libraries map database tables to classes. If a database has a table
called orders our program will have a class named Order. Rows in this table correspond to objects of the class—a particular order is represented as an object of class Order. Within that object, attributes are used to get and set the individual columns. Our Order object has methods to get and set the amount, the sales tax, and so on.


2.8 What is Active Record ?

Active Record is the ORM layer supplied with Rails. It closely follows the standard ORM model: tables map to classes, rows to objects, and columns to object attributes.


2.9 What is script directory ?

The scripts directory holds programs that are useful for developers. Run any of these scripts with no arguments to get usage information.
•benchmarker
Get performance benchmarks on one or more methods in your application.
•breakpointer
A client that lets you interact with running Rails applications. We
talk about this starting on page 189.
•console
Allows you to use irb to interact with your Rails application methods.
•destroy
Removes autogenerated files created by generate.
•generate
A code generator. Out of the box, it will create controllers, mailers,models, scaffolds, and web services
•profiler
Creates a runtime-profile summary of a chunk of code from your
application.
•runner
Executes a method in your application outside the context of the web.
You could use this to invoke cache expiry methods from a cron job,
or handle incoming e-mail.
•server
A WEBrick-based server that will run your application.


Q) What is ActiveRecord Migration?

Active Record Design Pattern:
Active record is an approach to accessing data in a database. A database object or view is wrapped into a class; thus an object instance is tied to a single row in the table. After creation of an object, a new row is added to the table upon save. Any object loaded gets its information from the database; when an object is updated, the corresponding row in the table is also updated. The wrapper class implements accessor methods or properties for each column in the table or view.
Migrations can manage the evolution of a schema used by several physical databases. It‘s a solution to the common problem of adding a field to make a new feature work in your local database, but being unsure of how to push that change to other developers and to the production server.


Q. What is request.xhr?

wheter it is a ajax request or not


Q) What is the Notation used for denoting class variables in Ruby?


1) a constant begins with an uppercase letter and it should not be defined inside a method
2) a local must begin with a lowercase letter or the _ underscore sign
3) a global begins with the $ sign; an uninitialized global has the value of “nil” and also produces a warning. can be reffered anywhere in the program
4) instances begin with the @ sign; an uninitialized instance has the value of “nil” and also produces a warning
5) a class variable begins with double @@ and have to be first initialized before being used in a method definition, otherwise you will get an error if you refer to it without initializing.


Q) What is the use of Destructive Method?


In ruby, we conventionally attach ‘!’ or ‘?’ to the end of certain method names. The exclamation point (!, sometimes pronounced aloud as “bang!”) indicates something potentially destructive, that is to say, something that can change the value of what it touches. chop! affects a string directly, but chop with no exclamation point works on a copy. Here is an illustration of the difference.
s1 = “forth”
s1.chop!
s2=s1.chop


Q. What is the use of load and require in Ruby?

require ‘rake’
will cause ruby to look for one of the files rake.rb or rake.so in thedirectories listed in $:. The script in bin is called simply rake, notrake.rb, and so require doesn’t even consider it.
load, instead, interpret its argument in a different way: it considers it tobe the whole basename of the file and doesn’t try to add any extension to it.So, the line
load ‘rake’
will make ruby look for a file called ‘rake’ (not rake.rb as before) in thedirectories listed in $:. This time bin/rake has the correct name and isloaded.


Q. Environment Variables in Ruby?

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.


Q. Difference between puts and print

puts a new line char,print is normal


Q. Explain about class libraries in ruby?

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.


Q. Explain about portability?

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.


Q. Explain about garbage collection feature of ruby?

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.


Q. Explain about the command line options?

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.


Q) How do you comment out a block of code?

A) Use =begin and =end.
=begin
def my_commented_out_method
end
=end
You could use successive # signs, but that’s just tedious:
#
# def my commented_out_method
# end
#


Q) How do you write to STDOUT in Ruby?

A) Actually two methods are available:
•puts writes with a newline
•print writes without a newline


Q) What’s the difference in scope for these two variables: @name and @@name?

A) @name is an instance variable and @@name is a class variable


Q) What two delimiters are used for blocks?
A) Curly braces {…} and “do”…”end”
Bonus: coding convention is to use curly braces if the code will fit on one line and “do”…”end” syntax if the block contains multiple lines.


Q) How do you capitalize all characters in a string?

A) “this is my string”.upcase
If the string is in a variable:
@my_string.upcase
Note: The method: upcase! is another alternative. See next question regarding methods that end with an exclamation.


Q) How do the following methods differ: @my_string.strip and @my_string.strip! ?

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


Q) What is the naming conventions for methods that return a boolean result?

A) 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
Rake and RubyGems
For two big reasons:
1.Task creation – With every large application you almost always end up writing scripts that you can run from the command line. You might want to clear the cache, run a maintenance task, or migrate the database. Rather than creating 10 separate shell scripts (or one big complex one) you can create a single “Makefile” in which you can organize things by task. Tasks then can be run by typing something like “make stupid” (which runs the stupid task).
2.Dependancy Task Tracking – When you start writing a library of maintenance tasks, you start to notice that some tasks might partially repeat themselves. For instance, the task “migrate” and the task “schema:dump” both require getting a connection to the database. I could create a task called “connect_to_database”, and set both “migrate” and “schema:dump” to depend on “connect_to_database”. Then the next time I run “migrate”, “connect_to_database” is run before the “migrate” task is run.

No comments:

Post a Comment