Thursday, September 18, 2014

Ruby/Rails Interview Questions

I’ve recently been helping interview some ruby/rails developers. I searched the web for some inspiration but I could not find any example questions that had real depth to them. I like my questions to be a point of discussion rather than one word answers. Most importantly I want a wide enough scope to let those talented individuals shine through. So here are some of the questions I’ve been trying out recently.
1. You are getting the chance to fly in the worlds first unmanned Airplane who’s systems are written only in ruby. Would you fly in it? Explain your reasoning
2. Ruby is great and everything but its nothing more than a prototyping language. Its just too hacky and dynamic for any real production system. Why bother with its messy Perl lineage and the lack of internationalisation support when you could just use Python? Discuss.
3. Ruby takes a unique approach to the problem of multiple inheritance. Explain ruby’s approach and the strengths and weaknesses of it.
4. Do you think adding behaviour to the builtin core Ruby classes is a good idea? Can you give some examples to backup your opinion.
5. Explain why in ruby nil.object_id is equal to 4. (Rather nasty question, really asking about C)
>> nil.object_id
=> 4
6. Twitter(http://www.twitter.com) is a website built on Ruby on rails. It is a
“Social networking and microblogging service utilising instant messaging, SMS or a web interface.”
Why do you think twitter (http://www.twitter.com) used Ruby on Rails?
Do you think it was a good decision?
7. Explain what ‘has_many’ is and what happens when it is run.
class Monkey < ActiveRecord::Base
  has_many :bananas
end
8. Given a simple website focused on a REST model and produced solely by using script/generate scaffold. Explain what happens in the rails application when a user submits a form with a POST request to: ‘/images/1’. State any assumptions you make.

9. If each language was represented as a person what type of person would each be and why?
  • Ruby person
  • Python person
  • Php person
  • Java person

Jobs Interview - More Ruby, Rails Questions and Answers

Name at least 3 ways to call a method in Ruby?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 class Greeter
    def greeting
       'hello' 
    end
 end 

greeter = Greeter.new 

# First way and most obvious 
greeter.greeting 

# Second way not so obvious but probably well known 
greeter.send :greeting 

# Third way the more obscure 
greeter.method(:greeting).call 

What is the difference between a Class, Module and Instance?

  • Class: is the blueprint from which individual objects are created. Classes in Ruby are first-class objects—-each is an instance of class Class.
  • Instance: is an object which was instantiated from a Class
  • Module: is a collection of methods and constants. You can’t make an instance of a module; the way you access the constants and methods inside it depends on it’s definition; module methods and variables can be accessed like this Module.method or Module.CONSTANT but if you want to access an instance method you should include the module to another class to use it.

What is the difference between include and extend?

include mixes a module as instance methods or constants and extend mixes a module as class methods; also you can extend a singleton object instance using this syntax. obj.extend Mod which will add the methods or constants to that single instance of that particular class.

What is a symbol and what are the risks of using them in web apps?

A symbol is mostly an immutable String they are mostly use to represent names. They are risky to be use on web apps in particular in Rails apps due to the following security issue:CVE-2013-1854 Symbol DoS vulnerability in Active Record
Update: This cannot lead an attacker to execute arbitrary code in the server you are running your app. That was a misinterpretation on my part. Thanks to Toby Ovod-Everett for pointing this out.

Can you name a recent security incident in Rails and explain the issue?

This was not very easy for me; because I normally don’t spend too much time on this type of stuff this days; even when I know the important of the topic; so the answer for this one is just to subscribe to the rails-security-ann mailing list

What does this do Hash[[1,2,3,4].zip([5,6,7,8])]?

Enumerable#zip Takes one element from enum and merges corresponding elements from each args.
1
  {1=>5, 2=>6, 3=>7, 4=>8}

What does the following do

1
(1..Float::INFINITY).map{ |i| i*i }.first(10)?
Nothing it will just hang your Ruby interpreter.

How to fix this

1
  (1..Float::INFINITY).map{ |i| i*i }.first(10)?
This only works on Ruby 2.0
1
(1..Float::INFINITY).lazy.map{ |i| i*i }.first(10)

What is the difference between a Proc and Lambda?

  • Block: Is a piece of code that can pass to a method as an argument. But can’t save it’s own state.
  • Proc: Is a block which can save state.
  • Lambda: Same thing as a Proc; the differences are that the lambda have diminutive returns; which means that even if you put a returnstatement inside the lambda it will keep running until the method in which was called finish it’s execution also lambdas check for the arguments passed to them; Proc doesn’t.

Ruby interview questions and answers

<Previous  Next>>
Overview of Ruby programming language.
An open source programming language that focuses on simplicity and productivity. The syntax of Ruby language is elegant which is natural to read and easy to write. Ruby is well known as language of careful balance. It has the blended features of Perl, Small talk, Eiffel, Ada and Lisp................
What is Rails?
Ruby on Rails is an open source web application framework for the Ruby programming language............
Describe class libraries in Ruby.
The Ruby standard library extends the foundation of the Ruby built-in library with classes and abstractions for a variety of programming needs, including network programming, operating system services, threads, and more............
Explain the concepts and capabilities of 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.............
Describe the environment variables present in Ruby.
RUBYOPT, RUBYLIB, RUBYPATH, RUBYSHELL,RUBYLIB_PREFIX...................
Interpolation is a very important process in Ruby, comment.
Interpolation is the process of inserting a string into a literal..............
What is the use of super in Ruby Rails? 
Ruby uses the super keyword to call the superclass implementation of the current method.............
What is the use of load and require in ruby? 
Reuire() 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..............
Explain the use of global variable $ in Ruby.
If you declare one variable as global we can access any where, where as class variable.............
Explain the difference between nil and false in ruby.  
False is a boolean datatype
Nil is not a data type..............

10 (best) Ruby (and Rails) interview questions (and answers)

As lately I was massively involved into the world of recruiting (both as candidate, and few month ago as a interviewer — sounds funny, right?), I decided to gather all these technical and non-tech questions I had during this trial in one place. Order is not important, I write this from the top of my head.
1. What is a class, what is an object and why we need modules
This may be simple, but it allows to start a conversation between two strangers involved into the same craft.
Answer: classes are a blue-print, they may hold data, likely they hold methods; classes are directly connected with an idea of objects, because object is an instance of a class. As objects are first-class citizens in Ruby, there is a main, root class Object, and all classes are inherited from this root entity. Modules, generally, are a tool for mix-ins and they provide something we call a namespace. Modules cannot be initialised the way we can do this with classes, but they provide a multiple inheritance.
2. Who’s _why and what’s up with his Shoes?
This is a tricky question, which may allow you to separate Ruby newcomers (and I’m not saying this is bad) from old-school warriors (and this also may be not so good, as it sounds). Here is why.
Answer: ‘why the lucky stiff’ (or ‘_why’) is the artist from a past decade, who used Ruby as his brush, and our minds as a canvas. He is both writer, cartoonist, artist, and computer programmer, famous by his contribution to many Open Source Ruby projects, “Why’s Poignant Guide to Ruby” piece of art and who disappeared in 2009. Shoes is a nice OSI project, initially made by _why, and it allows to create nice looking GUI applications using Ruby, for programmers of any age (from 3 to 100 years old). Shoes now are fine and quite active thanks to Shoes Team. You can find it on Github.
3. Why automated testing is a good and bad thing in the same time
Answer: automated testing (especially as the main tool of TDD/BDD) is an absolutely important part of modern applications development. This is your friend during refactoring, development and debugging. This is the way how you understand your codebase deeper, a way to predict bottle-necks, and sometimes it allows you to keep your code maintainable without unnecessary investments for years. In the same time, automated testing could be a source of terrible bugs and fails, as by itself, tests are the same code, as the ‘real’ code. This way, automating testing is an another tool to help your mind keep architecture and abstractions in the form of the code, speed-up things and automate sanity-tests. Which doesn’t mean you always have to pay your attention on manual testing.
4. What is Lambda? What is Proc? What is Block? What is Dash Rocket (stabby lambda)?
You can literally spend an hour talking about lambdas and procs. Here I’ll outline only the main statements.
Answer: they are from the same plate, however there are differences. Firstly, Proc is a nameless function, an anonymous method you use very frequently. Procs are objects, Blocks are not. Blocks are ‘business cards’ of Ruby, and they are, in fact, a syntax literals of Proc; they may take and return values. The main difference between Lambdas and Procs is Lambda explicitly check for arguments, while Proc is not. Stabby lambda ( -> ) is nothing more than another Lambda literal, from Ruby >= 1.9, you may easily think of this like of syntax sugar.
5. A practical task: web scraping. The task is to extract some information from some web page (pages). For example, to gather all top comments from some news site, or product's ratings from some online shop.
Answer: there is no ‘correct’ answer here (well, excepts this should work as expected). The main idea here is to see how it will be done, and the main pre-request from you is ‘go nuts’. This way, from this, by itself, simple task, you’ll be able to see how candidate does real things with Ruby. If candidate used plain Ruby, or it was done with Rack (Sinatra, Rails, whatever) web frontend? Was one of CLI frameworks used? What about testing? What about documentation? What about fallbacks? What about variables naming? The good thing is that even with this simple task, it allows a candidate to spend form 30 minutes to 3 days, depending on your pre-requests and candidate's mood, which could be a good measurement for you.
6. A Rails-specific question: how Date.today differs from Date.current?
Answer: It’s all about time zones: with Date.today you’ll have a system date, with Date.current it's system date, plus Rails’ time zone applied. Funny, but Time.zone.today should return you a date with a time zone too.
7. Skinny Controllers. Logic-less (as much as possible) templates. But where we’ll keep this zillions lines of code this way?
Answer: first answer could be, we’ll move controller’s code to models. Oookay. But we’ll have Fat Models (tm) this way, right? Then we’ll move everything to Rails’ concerns! And we’ll separate reusable code as libraries and gems. And this is true. The fact is it could be (sic!) even worse than to keep everything in models. One of the ways is, for example, to radically change architecture, introducing Rails' engines (and here you can talk about differences between gem and Rails Engine) or even partially move the code to the separated Rack application, and link your host with Rack app via internal API (here is the good place to talk about general application architecture). Or you can implement Data/Context/Interaction approach (here is the good place to talk about advanced architectural themes). After this, you’ll feel if it is reasonable to talk about Model-Views and Decorators.
8. What is 'self' in Ruby?
Answer: self refers to the current object. The thing is that Class is an object too, this way at class level, self is the class, but at the instance level it is the instance in context, already initialised somewhere in the memory.
9. What is database transactions and how it is represented in Rails
Answer: transactions are sets of changes, that must all be made together. It may, or may not change the contents of the database. When we talk about transactions, we usually mean we need to do something with database as single unit execution. A classy transaction is when you withdraw money from one bank account to another, and you need to substract from one bank account and add to another in the same time. In Rails you have ActiveRecord::Base.transaction, which allows you to easily pass multiple actions in a block, and they’ll be executed a transactional way.
10. Tell me about your development environment.
Answer: this question is good both for the begining and the end of interview. Usually, a good programmer has an attitude to his workplace. This could be a minimalistic approach, like 'I use a raw vim config, no fancy plugins, because it allows me to have ‘my’ workplace on any default config', or candidate could be a tiling window manager fan, hacking his i3/Xmonad/awesome config daily, creating custom emacs themes for every single period of the day, depending of lighting, with the data received from Arduino-based sensor. In any case, you’ll both have some fun, talking about this.

7 Great Ruby on Rails Interview Questions*

What paths (HTTP verb and URL) will be defined by the following snippet in config/routes.rb?
resources :posts do
  member do
    get 'comments'
  end
  collection do
    post 'bulk_upload'
  end
end
Using the resource method to define routes will automatically generate routes for the standard seven restful actions:
  1. GET /posts
  2. POST /posts
  3. GET /posts/new
  4. GET /posts/:id/edit
  5. GET /posts/:id
  6. PATCH/PUT /posts/:id
  7. DELETE /posts/:id
Note that Rails also supports the (relatively) new URL verb PATCH for partial updates to records. (In theory, a PUT request should only be valid if the entire record is included in the request.)
The extra routes defined inside of the block passed to resources will generate one route valid for individual posts (GET /posts/:id/comments) as well as one defined for the top-level resource (POST /posts/bulk_upload).
What is the difference between Ruby’s Hash and ActiveSupport’s HashWithIndifferentAccess?
The Hash class in Ruby’s core library retrieves values by doing a standard == comparison on the keys. This means that a value stored for a Symbol key (e.g. :my_value) cannot be retrieved using the equivalent String (e.g. ‘my_value’). On the other hand, HashWithIndifferentAccess treats Symbol keys and String keys as equivalent so that the following would work:
h = HashWithIndifferentAccess.new
h[:my_value] = 'foo'
h['my_value'] #=> will return "foo"

What’s the problem with the following controller code? What would be the consequence of leaving this code in a production app? How would you fix it?
class MyController < ApplicationController
  def options
    options = {}
    available_option_keys = [:first_option, :second_option, :third_option]
    all_keys = params.keys.map(&:to_sym)
    set_option_keys = all_keys & available_option_keys
    set_option_keys.each do |key|
      options[key] = params[key]
    end
    options
  end
end
It’s dangerous to convert user supplied parameters to symbols, since Symbol objects in Ruby are not garbage collected. An attacker could send a series of requests with random keys that would be turned into symbols, quickly exhausting your server’s available memory and taking down your site.
There are two ways that this could be fixed. The first would be to use slice to eliminate values from the params hash that are not valid option keys. This would look something like:
params.slice(*available_option_keys)
An alternative, some would argue better, option would simply be to use String keys for your options. Unless you have an extremely large number of possible option keys, you won’t actually save that much memory by using Symbol keys instead.
What is CSRF? How does Rails protect against it?
CSRF stands for Cross-Site Request Forgery. This is a form of an attack where the attacker submits a form on your behalf to a different website, potentially causing damage or revealing sensitive information. Since browsers will automatically include cookies for a domain on a request, if you were recently logged in to the target site, the attacker’s request will appear to come from you as a logged-in user (as your session cookie will be sent with the POST request).
In order to protect against CSRF attacks, you can add protect_from_forgery to your ApplicationController. This will then cause Rails to require a CSRF token to be present before accepting any POSTPUT, or DELETE requests. The CSRF token is included as a hidden field in every form created using Rails’ form builders. It is also included as a header in GET requests so that other, non-form-based mechanisms for sending a POST can use it as well. Attackers are prevented from stealing the CSRF token by browsers’ “same origin” policy.
How would you define a Person model so that any Person can be assigned as the parent of another Person (as demonstrated in the Rails console below)? What columns would you need to define in the migration creating the table for Person?
irb(main):001:0> john = Person.create(name: "John")
irb(main):002:0> jim = Person.create(name: "Jim", parent: john)
irb(main):003:0> bob = Person.create(name: "Bob", parent: john)
irb(main):004:0> john.children.map(&:name)
=> ["Jim", "Bob"]
And for a more advanced challenge: Update the Person model so that you can also get a list of all of a person’s grandchildren, as illustrated below. Would you need to make any changes to the corresponding table in the database?
irb(main):001:0> sally = Person.create(name: "Sally")
irb(main):002:0> sue = Person.create(name: "Sue", parent: sally)
irb(main):003:0> kate = Person.create(name: "Kate", parent: sally)
irb(main):004:0> lisa = Person.create(name: "Lisa", parent: sue)
irb(main):005:0> robin = Person.create(name: "Robin", parent: kate)
irb(main):006:0> donna = Person.create(name: "Donna", parent: kate)
irb(main):007:0> sally.grandchildren.map(&:name)
=> ["Lisa", "Robin", "Donna"]
Normally, the target class of an ActiveRecord association is inferred from the association’s name (a perfect example of “convention over configuration”). It is possible to override this default behavior, though, and specify a different target class. Doing so, it is even possible to have relationships between two objects of the same class.
This is how it is possible to set up a parent-child relationship. The model definition would look like:
class Person < ActiveRecord::Base
  belongs_to :parent, class: Person
  has_many :children, class: Person, foreign_key: :parent_id
end
It’s necessary to specify the foreign_key option for the has_many relationship because ActiveRecord will attempt to use :person_id by default. In the migration to create the table for this model, you would need to define, at minimum, a column for the name attribute as well as an integer column for parent_id.
Self-referential relationships can be extended in all the same ways as normal two-model relationships. This even includes has_many ... :through => ... style relationships. However, because we are circumventing Rails’ conventions, we will need to specify the source of the :through in the case of adding a grandchild relationship:
class Person < ActiveRecord::Base
  belongs_to :parent, class: Person
  has_many :children, class: Person, foreign_key: :parent_id
  has_many :grandchildren, class: Person, through: :children, source: :children
end
Consequently, since this is still just using the parent_id defined in the first case, no changes to the table in the database are required.
Create a route to be able to display pages with different information about different types of beer. The route should recognize URL paths like /beer/<beer_type> and should use the same controller action for each type of beer with the actually beer type passed into the controller action as a parameter. The valid beer types are:
  • IPA
  • brown_ale
  • pilsner
  • lager
  • lambic
  • hefeweizen
Any other type of beer specified should generate a 404 status code.
One option would be to generate a simple get route that specifies the controller action to call and passes the kind of beer as a parameter:
get 'beers/:kind' => 'beers#kind'
Then, within the context of the controller action, if the kind parameter is not included in the list of valid kinds, the action can raise a ActionController::RoutingError, which will redirect to 404 in production.
Alternatively, a simpler solution is to check against the list of valid kinds in the definition of the route. This can be accomplished using the constraints option as follows:
kinds = %w|IPA brown_ale pilsner lager lambic hefweizen|
get 'beers/:kind' => 'beers#kind', constraints: {kind: Regexp.new(kinds.join('|'))}
This code calls the BeersController#kind action method with params['kind'] set to a string representing the beer type given in the URL path. The key is using the constraints option for the route to specify a regular expression to use to verify the route is correct. In this case, the lambda checks to see that the kind parameter is included in the list of valid beer types.
Or perhaps an even better solution would be to use resource routing. This has the added benefit of providing URL generation helpers, but at the cost of requiring that the parameter name for the beer be passed as :id. This would look something like:
kinds = %w|IPA brown_ale pilsner lager lambic hefweizen|
resource :beer, only: [:show], constraints: {id: Regexp.new(kinds.join('|'))}

What’s the issue with the controller code below? How would you fix it?
class CommentsController < ApplicationController
  def users_comments
    posts = Post.all
    comments = posts.map(&:comments).flatten
    @user_comments = comments.select do |comment|
      comment.author.username == params[:username]
    end
  end
end

This is a classic example of the notorious “n+1” bug. The first line will retrieve all of the Post objects from the database, but then the very next line will make an additional request for each Post to retrieve the corresponding Comment objects. To make matters worse, this code is then making even more database requests in order to retrieve the Author of each Comment.
This can all be avoided by changing the first line in the method to:
posts = Post.includes(comments: [:author]).all
This tells ActiveRecord to retrieve the corresponding Comment and Author records from the database immediately after the initial request for all Posts, thereby reducing the number of database requests to just three.
Please note that the above answer is only one of a few ways that it is possible to avoid incurring an “n+1” penalty, and each alternative will have its own caveats and corner cases. The above answer was selected to be presented here since it requires the smallest change to the existing code and makes no assumptions regarding the reverse association of Comment to Post.