Ruby Interview Questions
Ruby Interview Questions
class CarModel
FEATURES = ["engine", "wheel", "airbag", "alarm", "stereo"]
FEATURES.each do |feature|
define_method("#{feature}_info=") do |info|
instance_variable_set("@#{feature}_info", info)
end
define_method("#{feature}_info") do
instance_variable_get("@#{feature}_info")
end
define_method("#{feature}_price") do
instance_variable_get("@#{feature}_price")
end
end
end
How do they relate?
So, how does this all fit together?
Out of these pieces, a web request will hit your web server first. If the
request is something Rails can handle, the web server will do some
processing on the request, and hand it off to the app server. The app server
uses Rack to talk to your Rails app. When your app is done with the
request, your Rails app sends the response back through the app server
and the web server to the person using your app.
More specifically, Nginx might pass a request to Unicorn. Unicorn gives the
request to Rack, which gives it to the Rails router, which gives it to the
right controller. Then, your response just goes back through the other way.
A member route will require an ID, because it acts on a member. A collection route doesn't
because it acts on a collection of objects. Preview is an example of a member route,
because it acts on (and displays) a single object. Search is an example of a collection route,
because it acts on (and displays) a collection of objects.
Resource routing allows you to quickly declare all of the common routes for a given resourceful
controller. Instead of declaring separate routes for your index, show, new, edit, create, u pdate and destroy
actions, a resourceful route declares them in a single line of code:
resources :photos
Sometimes, you have a resource that clients always look up without referencing an ID. A common
example, /profile always shows the profile of the currently logged in user. In this case, you can
use a singular resource to map /profile (rather than /profile/:id) to the show action.
resource :profile
It's common to have resources that are logically children of other resources:
resources :magazines do
resources :ads
end
You may wish to organize groups of controllers under a namespace. Most commonly, you might
group a number of administrative controllers under an admin namespace. You would place these
controllers under the a pp/controllers/admin directory, and you can group them together in your router:
namespace "admin" do
resources :posts, :comments
end
By default the :id parameter doesn't accept dots. If you need to use dots as part of the :id
parameter add a constraint which overrides this restriction, e.g:
Save does not throw any error in the case above, but cancels the
save. Also, the methods for validations can be bypassed.
RESTful API
A RESTful API is an application program interface (API) that uses HTTP requests to
GET, PUT, POST and DELETE data.
It means when a RESTful API is called, the server will transfer to the client a
representation of the state of the requested resource.
1) Explain what is Ruby on Rails?
● Ruby: It is an object oriented programming language inspired by PERL and PYTHON.
● Ruby is a pure object-oriented language and everything appears to Ruby as
an object. Every value in Ruby is an object, even the most primitive things:
strings, numbers and even true and false. Even a class itself is an object that
is an instance of the Class class. This chapter will take you through all the
major functionalities related to Object Oriented Ruby.
● A class is used to specify the form of an object and it combines data
representation and methods for manipulating that data into one neat
package. The data and methods within a class are called members of the
class.
● Rails: It is a framework used for building web application
2) Explain what is class libraries in Ruby?
Class libraries in Ruby consist of a variety of domains, such as data types, thread
programming, various domains, etc.
3) Mention what is the naming convention in Rails?
● Variables: For declaring Variables, all letters are lowercase, and words are separated
by underscores
● Class and Module: Modules and Classes uses MixedCase and have no underscore;
each word starts with a uppercase letter
● Database Table: The database table name should have lowercase letters and
underscore between words, and all table names should be in the plural form for example
invoice_items
● Model: It is represented by unbroken Mixed Case and always have singular with the
table name
● Controller: Controller class names are represented in plural form, such that
OrdersController would be the controller for the order table.
4) Explain what is “Yield” in Ruby on Rails?
Yield is A Ruby method that receives a code block invokes it by calling it with the “Yield”.
5) Explain what is ORM (Object-Relationship-Model) in Rails?
ORM or Object Relationship Model in Rails indicate that your classes are mapped to the
table in the database, and objects are directly mapped to the rows in the table.
23) Explain how you can run Rails application without creating databases?
You can execute your application by uncommenting the line in environment.rb
path=> rootpath conf/environment.rb
config.frameworks = [ action_web_service, :action_mailer, :active_record]
24) Mention what is the difference between the Observers and Callbacks in Ruby on
Rails?
● Rails Observers: Observers is as as Callback, but it is used when method is not directly
associated to object lifecycle. Also, the observer lives longer, and it can be detached or
attached at any time. For example, displaying values from a model in the UI and
updating model from user input.
● Rails Callback: Callbacks are methods, which can be called at certain moments of an
object’s life cycle for example it can be called when an object is validated, created,
updated, deleted, A call back is short lived. For example, running a thread and giving a
call-back that is called when thread terminates.
25) Explain what is rake in Rails?
Rake is a Ruby Make; it is a Ruby utility that substitutes the Unix utility ‘make’, and uses a
‘Rakefile’ and ‘.rake files’ to build up a list of tasks. In Rails, Rake is used for normal
administration tasks like migrating the database through scripts, loading a schema into the
database, etc.
26) Explain how you can list all routes for an application?
To list out all routes for an application you can write rake routes in the terminal.
27) Explain what is sweeper in Rails?
Sweepers are responsible for expiring or terminating caches when model object changes.
28) Mention the log that has to be seen to report errors in Ruby Rails?
Rails will report errors from Apache in the log/Apache.log and errors from the Ruby code in
log/development.log.
30) Mention what is the function of garbage collection in Ruby on Rails?
The functions of garbage collection in Ruby on Rails includes
● It enables the removal of the pointer values which is left behind when the execution of
the program ends
● It frees the programmer from tracking the object that is being created dynamically on
runtime
● It gives the advantage of removing the inaccessible objects from the memory, and allows
other processes to use the memory
31) Mention what is the difference between redirect and render in Ruby on Rails?
● Redirect is a method that is used to issue the error message in case the page is not
found to the browser. It tells the browser to process and issue a new request.
● Render is a method used to make the content. Render only works when the controller is
being set up properly with the variables that require to be rendered.
32) Mention what is the purpose of RJs in Rails?
RJs is a template that produces JavaScript which is run in an eval block by the browser in
response to an AJAX request. It is sometimes used to define the JavaScript, Prototype and
helpers provided by Rails.
49) Mention what is the Notation used for denoting class variables in Ruby?
In Ruby,
● A constant should begin with an uppercase letter, and it should not be defined inside a
method
● A local must begin with the _ underscore sign or a lowercase letter
● A global variable should begin with the $ sign. An uninitialized global has the value of
“nil” and it should raise a warning. It can be referred anywhere in the program.
● A class variable should begin with double @@ and have to be first initialized before
being used in a method definition
50) Mention what is the difference between Procs and Blocks?
The difference between Procs and Blocks,
● Block is just the part of the syntax of a method while proc has the characteristics of a
block
● Procs are objects, blocks are not
● At most one block can appear in an argument list
● Only block is not able to be stored into a variable while Proc can
51) Mention what is the difference between a single quote and double quote?
A single-quoted strings don’t process ASCII escape codes, and they don’t do string
interpolation.
51) Mention what is the difference between a gem and a plugin in Ruby?
● Gem: A gem is a just ruby code. It is installed on a machine, and it’s available for all ruby
applications running on that machine.
● Plugin: Plugin is also ruby code, but it is installed in the application folder and only
available for that specific application.
ch = Child.new
ch.try_this()
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
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
There are two files where variables and configuration settings are stored.
The same file is also used for configuring various environment settings such as:
You would specify various config settings the development environment in this file.
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.
64) What’s Rack?
Rack is a Ruby package that provides an easy-to-use interface to the Ruby Net::HTTP library.
The BasicObject class is the parent class of all classes in Ruby. Its methods are therefore
available to all objects unless explicitly overridden. Prior to Ruby 1.9, Object class was the root
of the class hierarchy. The new class BasicObject serves that purpose, and Object is a
subclass of BasicObject. BasicObject is a very simple class, with almost no methods of its
own. When you create a class in Ruby, you extend Object unless you explicitly specify the
super-class, and most programmers will never need to use or extend BasicObject.
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?".
As of today, all support for Ruby 1.9.3 has ended. Bug and security fixes from more recent Ruby
versions will no longer be backported to 1.9.3.
We highly recommend that you upgrade to Ruby 2.0.0 or above as soon as possible. Please
contact us if you’d like to continue maintaining the 1.9.3 branch for some reason you can’t
upgrade.
There are several benefits when using more recent versions of Ruby:
● Security (e.g. old versions might have unfixed issues) and maintenance
● Compatibility with gems you want to use (e.g. current versions might use kwargs that
were introduced in Ruby 2.0)
● Performance (newer versions are usually faster, see source)
● Documentation and learning (it might be harder to find solutions to problems or good
blog articles for old versions)
That said: Try to keep up-to-date and use the most recent version that is supported by your
environment and dependencies.
69 )Diff in rails 4?
##Notable Changes in Rails 4
###Ruby 1.9.3 Minimum
###No more vendor/plugins
70 )What is Bundler?
Bundler is a program for managing gem dependencies in your Ruby projects. With Bundler you
can specify which gems your program needs, what versions they should be at, it can help you
install them, load them at runtime and distribute them with your software. Basically, it takes all of
the guesswork out of installing the gems needed to run your Ruby projects.
71 )RubyGems?
The RubyGems software allows you to easily download, install, and use ruby software
packages on your system. The software package is called a “gem” and contains a package
Ruby application or library. ... Some gems provide command line utilities to help automate tasks
and speed up your work.
72 )What is a Proc?
Everyone usually confuses procs with blocks, but the strongest rubyist can grok the true
meaning of the question.
Essentially, Procs are anonymous methods (or nameless functions) containing code.
They can be placed inside a variable and passed around like any other object or scalar
value. They are created by Proc.new, lambda, and blocks (invoked by the yield
keyword).
lways refers to the current object. But this question is more difficult than it seems
a
self
because Classes are also objects in ruby. (Kudos to Stephen)
class WhatIsSelf
def test
puts "At the instance level, self is #{self}"
end
def self.test
puts "At the class level, self is #{self}"
end
end
WhatIsSelf.test
#=> At the class level, self is WhatIsSelf
WhatIsSelf.new.test
#=> At the instance level, self is #<WhatIsSelf:0x28190>
74) What is a module? What is its purpose? How do we use them with our classes?
Create a module for the class you created in exercise 1 and include it properly.
A module allows us to group reusable code into one place. We use modules in our
classes by using the include reserved word, followed by the module name.
Modules are also used as a namespace.
module Study
end
class MyClass
include Study
end
my_obj = MyClass.new
Lambda
Despite the fancy name, a lambda is just a function... peculiarly... without a name.
They're anonymous, little functional spies sneaking into the rest of your code.
Lambdas in Ruby are also objects, just like everything else! The last expression of a
lambda is its return value, just like regular functions. As boring and familiar as that all
sounds, it gives us a lot of power.
As objects, lambdas have methods and can be assigned to variables. Let's try it!
l = lambda do |string|
if string == "try"
return "There's no such thing"
else
return "Do or do not."
end
end
puts l.call("try") # Feel free to experiment with this
Adds a class method for retrieving and querying objects. A scope represents a
narrowing of a database query, such as where(:color =>
:red).select('shirts.*').includes(:washing_instructions).
ActiveRecord Rails 3 scope vs class
method
There was more of a difference in Rails 2.x, since named_scopes did not execute your queries
(so you could chain them), whereas class methods generally did execute the queries (so you
could not chain them), unless you manually wrapped your query in a scoped(...) call.
In Rails 3, everything returns an ActiveRecord::Relation until you need the actual results, so
scopes can be chained against class methods and vice versa (as long as the class methods
return ActiveRecord::Relation objects, not some other object type (like a count)).
Generally, I use scope entries for simple one-liners to filter down my result set. However, if I'm
doing anything complicated in a "scope" which may require detailed logic, lambdas, multiple
lines, etc., I prefer to use a class method. And as you caught, if I need to return counts or
anything like that, I use a class method.
Rails provides four different ways to load association data. In this blog we are going to look at
each of those.
Preload
Preload loads the association data in a separate query.
User.preload(:posts).to_a
# =>
SELECT "users".* FROM "users"
SELECT "posts".* FROM "posts" WHERE "posts"."user_id" IN (1)
This is how includes loads data in the default case.
Since preload always generates two sql we can’t use posts table in where condition. Following
query will result in an error.
User.preload(:posts).where("posts.desc='ruby is awesome'")
# =>
SQLite3::SQLException: no such column: posts.desc:
SELECT "users".* FROM "users" WHERE (posts.desc='ruby is awesome')
With preload where clauses can be applied.
User.preload(:posts).where("users.name='Neeraj'")
# =>
SELECT "users".* FROM "users" WHERE (users.name='Neeraj')
SELECT "posts".* FROM "posts" WHERE "posts"."user_id" IN (3)
Includes
Includes loads the association data in a separate query just like preload.
However it is smarter than preload. Above we saw that preload failed for query
User.preload(:posts).where("posts.desc='ruby is awesome'"). Let’s try same with includes.
User.includes(:posts).where('posts.desc = "ruby is awesome"').to_a
# =>
SELECT "users"."id" AS t0_r0, "users"."name" AS t0_r1, "posts"."id" AS t1_r0,
"posts"."title" AS t1_r1,
"posts"."user_id" AS t1_r2, "posts"."desc" AS t1_r3
FROM "users" LEFT OUTER JOIN "posts" ON "posts"."user_id" = "users"."id"
WHERE (posts.desc = "ruby is awesome")
As you can see includes switches from using two separate queries to creating a single LEFT
OUTER JOIN to get the data. And it also applied the supplied condition.
So includes changes from two queries to a single query in some cases. By default for a simple
case it will use two queries. Let’s say that for some reason you want to force a simple includes
case to use a single query instead of two. Use references to achieve that.
User.includes(:posts).references(:posts).to_a
# =>
SELECT "users"."id" AS t0_r0, "users"."name" AS t0_r1, "posts"."id" AS t1_r0,
"posts"."title" AS t1_r1,
"posts"."user_id" AS t1_r2, "posts"."desc" AS t1_r3
FROM "users" LEFT OUTER JOIN "posts" ON "posts"."user_id" = "users"."id"
In the above case a single query was done.
Eager load
eager loading loads all association in a single query using LEFT OUTER JOIN.
User.eager_load(:posts).to_a
# =>
SELECT "users"."id" AS t0_r0, "users"."name" AS t0_r1, "posts"."id" AS t1_r0,
"posts"."title" AS t1_r1, "posts"."user_id" AS t1_r2, "posts"."desc" AS t1_r3
FROM "users" LEFT OUTER JOIN "posts" ON "posts"."user_id" = "users"."id"
This is exactly what includes does when it is forced to make a single query when where or order
clause is using an attribute from posts table.
Joins
Joins brings association data using inner join.
User.joins(:posts)
# =>
SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
In the above case no posts data is selected. Above query can also produce duplicate result. To
see it let’s create some sample data.
def self.setup
User.delete_all
Post.delete_all
Cron
If you’re reading this article, it’s probably because you’ve heard of cron jobs, cron tasks, or
crontab. Cron is a piece of software written for *nix-type operating systems to help with the
scheduling of recurring tasks.You may want to use cron to schedule certain recurring actions in
your Rails application, such as checking each day for expired accounts or clearing out expired
sessions from your database.
It’s pretty easy to start working with cron jobs. You can start editing your cron tasks using the
crontab command:
Turbo link
Turbolinks makes following links in your web application faster. Instead of letting the browser
reload the JavaScript and CSS between each page change, and spend extra HTTP requests
checking if the assets are up-to-date, we keep the current instance alive and replace only the
body and the title in the head.
before_filter :confirm_logged_in, :except => [:login, :attempt_login, :logout] def index .... end
1
2
3
4
5
Runtime Speed - The most cited argument against Ruby on Rails is that it's "slow". I would agree,
certainly when compared to the runtime speed of NodeJS or GoLang. Though in reality, the
performance of a Ruby application is incredibly unlikely to be a bottleneck for a business. In 99% of
cases, the bottleneck is going to be elsewhere, such as within the engineering team, IO, database or
server architecture etc. When you get to a significant enough scale to have to worry about Rails
runtime speed, then you're likely to have a incredibly successful application (think Twitter volume)
and will have many scaling issues to deal with.
● Boot Speed - The main frustration we hear from developers working in Rails is the
boot speed of the Rails framework. Depending on the number of gem dependencies
and files, it can take a significant amount of time to start, which can hinder
developer performance. In recent versions of Rails this has been somewhat
combatted by the introduction of Spring, but we feel this could still be faster.
● Documentation - It can be hard to find good documentation. Particularly for the
less popular gems and for libraries which make heavy use of mixins (which is most
of Rails). You'll often end up finding the test suite acts as documentation and you'll
rely on this to understand behaviour. This isn't itself a bad thing, as the test suite
should be the most up-to-date representation of the system, however, it can still be
frustrating having to dive into code, when sometimes written documentation would
have been much quicker.
● Multithreading - Rails supports multithreading, though some of the IO libraries
do not, as they keep hold of the GIL (Global Interpreter Lock). This means if you're
not careful, requests will get queued up behind the active request and can introduce
performance issues. In practice, this isn't too much of a problem as, if you use a
library that relies on GLI, you can switch to multiprocess setup. The knock-on effect
of this is your application ends up consuming more compute resources than
necessary, which can increase your infrastructure costs.
● ActiveRecord - AR is used heavily within the Ruby on Rails world and is a hard
dependency for many of the RubyGems. Although we think it's a great design
pattern, the biggest drawback we see is that your domain becomes tightly coupled to
your persistence mechanism. This is far from ideal and can lead to bad architecture
decisions. There are many ways to work around this, some of which are included in
this 7 Patterns to Refactor Fat ActiveRecord Modelsarticle. We would like to see
Rails become less reliant on ActiveRecord.
●
● A lambda will return normally, like a regular method. But a proc will try to return from the
current context.
‘return’ inside of a lambda triggers the code right outside of the lambda code
‘return’ inside of a proc triggers the code outside of the method where the proc is
being executed