53 Ruby on Rails Interview Questions and Answers

53 Ruby on Rails Interview Questions and Answers

Questions you may be asked in a junior or intermediate Ruby on Rails role interview

Image for post

I?ve interviewed over a hundred developers for Ruby on Rails positions and interviewed for more than a couple of positions myself. These are questions I?ve either received or given.

It may surprise you how many big companies still use Rails in 2020 including Shopify, Airbnb, GitHub, Dribble, Etsy, Kickstarter, Zendesk, Twitch, 500px, and Instacart.

I hope this is a helpful guide whether you?re interviewing for a job or interviewing candidates to hire.

Let?s get to the questions, in no particular order.

1. Walk me through the request/response cycle for accessing a list of articles in a blogging application?

The user clicks a button and a GET request is made to the URL,/articles. The web server receives this request. Rails then executes the corresponding controller action, #index, based on URL/controller mapping in routes.rb.

The controller calls Article.all which loads a collection of articles from the database via the Article model. This collection is assigned to an instance variable.

A view is rendered to the requesting user which interpolates the instance variable values to display the list of articles.

2. Everything (almost) is an object in Ruby. Please explain

In object-oriented programming, an object is an instance of a class. In Ruby, all classes are instances of the class Class.

For example:

7.class => Fixnum7.class.class => Class

A few things are not objects like blocks, methods, and conditional statements (i.e.: if, else).

This question is asked to see if you understand that most things in Ruby behave similarly, which makes Ruby easier to pick up than other languages.

3. Is Ruby statically or dynamically typed?

Ruby is dynamically typed. This is why you can change the type of a variable on the fly.

In Ruby, the following lines of code, run one after the other, do not throw an error.

x = 1x = “foo”

4. Tell me about getters and setters in Ruby

A getter allows accessing an instance variable. A setter allows setting an instance variable.

It?s possible to manually define getter and setter methods.

But Ruby provides three accessor methods that do the same thing and are cleaner: attr_reader (getter), attr_writer (setter), and attr_accessor (setter and getter).

5. What happens when you call a method in Ruby?

A message containing the method?s name is sent to the object. If that method exists on the object, the object calls it.

This is more apparent if considering Ruby?s send method.

obj.hello # => ‘hello’obj.send(:hello) # => ‘hello’

6. How can you list all routes in an app?

$ rake routes

It?s also possible to append to this, | grep <keyword>, to filter returned routes.

7. What is a Gemfile?

A Gemfile is where we specify dependencies for a Ruby application. It is located in the project?s root directory.

8. What is Gemfile.lock?

It contains records of exact versions of gems installed. This is so the same versions can be installed if another machine clones the project.

In contrast, specifying a gem in a Gemfile without pegging to a specific version will just install the latest version of a gem.

9. What are some Rails design patterns you?ve used?

There are a number of design patterns in Rails including service objects, value objects, form objects, query objects, view objects, policy objects, and decorators.

Digging into each one is the topic of a full post but here is a great tutorial with examples.

10. How does Rails manage database state?

The developer manually generates and adds instructions to migration files.

These instruct ActiveRecord how to modify the existing database state. For this reason, deleting or modifying previous migrations can put the database into a bad state and is not recommended.

Manually creating migration files is in contrast to other frameworks like Django, where the end state of the database is specified and then migrations are auto-generated to make the required changes.

11. What is the difference between count, length, and size?

  • count: Executes an SQL query to count the number of records. This is useful if the number of records may have changed in the DB vs. memory.
  • length: Returns the number of items in a collection in memory. It?s lighter weight than count because no database transaction is performed. It can also be used to count characters in a string.
  • size: This is an alias for length and does the same thing.

12. How have you implemented authorization in the past?

Authorization (not to be confused with authentication) pertains to allowing different types of users different levels of access in an app. It?s useful when there are lots of types of users with differing levels of access.

A few gems like Pundit and CanCanCan implement authorization.

13. What are callbacks?

?Callback? is a misleading term. They are hooks into the object lifecycle on which you can execute methods.

A number of callbacks exist around creating, updating, and destroying an object such as before_validation, after_save, and after_destroy.

They are useful for conditional logic like creating an associated Contact record when a User record is created.

14. When would you use a before_save vs. after_save callback?

Updating an object after it?s been saved requires an additional database transaction to persist the update. So, if you are updating an object?s attribute, a before_save callback is more efficient.

But sometimes information does exist on the object until it?s persisted (i.e.: id). So, if an id is required to create an associated record, that would have to be performed in an after_save callback.

15. What are initializers in Rails?

Initializers hold configuration logic and only run when an app is booted. This means the Rails server needs to be restarted if initializers are changed. They exist in the /config/initializers directory.

16. What is the difference between delete and destroy?

  • delete: Deletes a record.
  • destroy: Deletes a record and executes callbacks.

The most common callback on destroy in Rails apps is specified on associations in model files. For example, the below destroys related comments when an article is destroyed.

class Article < < BaseController has_many :comments, dependent: :destroyend

17. What is the meaning of ?Fat models, skinny controllers??

Business logic should exist in models, not controllers. This makes logic easier to unit test and is more re-usable.

Controllers are merely the hands that pass information between views and models.

This is generally given as advice to new Rails developers. It?s not actually recommended, particularly in large apps.

18. What is the meaning of ?skinny controllers, skinny models??

As a codebase grows, fat models get out of hand, start doing too many things and become unmanageable. Models should handle persistence without being bloated with logic.

Models can be made skinnier by keeping the single responsibility principle in mind and moving logic out of models, and into other design patterns like service objects.

19. What is the difference between class methods and instance methods?

Class methods are available on classes, and instance methods are available on instances (of course).They are typically used for different purposes.

For a class, Article, an instance method may count the number of words in the body of a specific article. While a class method may count the number of articles by a particular writer across all articles (notice the difference in scope?).

Class methods are denoted by def self.method_name.

20. What is a PORO?

PORO stands for ?Plain Old Ruby Object?.

Although almost everything in Ruby is an object, ActiveRecord tends to use a lot of complex objects. So, the term PORO is typically to stress a small, simple object used to support business logic.

21. Does Ruby allow multiple inheritances?

Ruby does not allow inheriting from more than one parent class, but it does allow module mixins with include and extend.

22. Is Ruby strongly or weakly typed?

Ruby is strongly typed. An error will be thrown if you try to calculate ?hello? + 3.

In contract, JavaScript is weakly typed and would simply evaluate the same calculation to ?hello3?.

23. What frameworks have you used for backgrounding jobs?

  • Delayed::Job: Easy to set up and use. Queues are stored in a database table. If the same database is used for Delayed::Job and production, then a large number of jobs could turn the database into a bottleneck.
  • Sidekiq: Uses Redis to queue jobs. Redis is an in-memory data store so it?s very fast. Sidekiq adds complexity to infrastructure because Redis needs to be added.
  • Sucker Punch: Runs as a Ruby process and keeps all jobs in memory. Jobs are lost if the process crashes. Not recommended for critical tasks.

24. How to declare a constructor on a Ruby class?

A constructor is defined via an initialize method which is called when a new instance of a class is initialized. Defining this method is not required. It?s often used to provide attribute values on new instances.

25. What logic goes into a helper?

Helper logic should support views only.

A good candidate for a helper is date formatting logic required in several different views.

26. What is ActiveRecord?

Active Record is an ORM (object-relational mapping) that maps models to database tables. It simplifies setting up an app because we no longer have to write SQL directly to load, save, or delete objects.

It also provides some protection against SQL injection.

27. When do we use ?self? in Ruby?

  • Use self when defining and calling class methods.
  • In a class, self refers to the current class so it?s required when a class method calls another class method.
  • self.class.method is required when an instance calls a class method.

28. What is Rack?

Rack is an API sitting between the web server and Rails. It allows plugging in and swapping frameworks like Rails with Sinatra, or web servers like Unicorn with Puma.

29. What is MVC?

MVC (Model-View-Controller) is a software design pattern that Rails is built around. It splits the handling of information into three pieces.

The model manages data and logic. The view displays information. The controller takes input and prepares data for a model or view

Image for post

30. What is a block in Ruby?

A block is the code between two braces, {?}, or between do and end. You?re passing a block every time you call .each.

Blocks have their own scope and variables only defined inside a block are not accessible outside. But variables defined outside a block can be modified inside a block.

{|x| puts x} # a block

31. What is the difference between a proc and a lambda?

Both procs and lambdas are stored blocks but syntax and behavior differs slightly.

A lambda returns from itself but a proc returns from the method it?s inside.

Notice that method_proc returns 1 because calling the proc ends execution within the method.

32. What is yield in Ruby?

yield accesses a block passed to a method. It?s typically used in layout files in a Rails application.

Notice the ?its me? is printed when yield is called.

33. What is content_for for?

It allows defining and rendering content in views. This is useful for defining content in one place and rendering it in many.

34. What is the difference between Hash and JSON?

Hash is a Ruby class, a collection of key/value pairs that allows accessing values by keys.

JSON is a string in a specific format for sending data.

35. What is Active Job?

Allows creating background jobs and queuing them on a variety of back ends like Delayed::Job or Sidekiq.

It?s typically used to execute code that doesn?t need to be executed in the main web thread. A common use case is sending notification emails to users.

36. What do you like about Rails?

I?ve used a number of web frameworks and nothing is as fast for building an MVP as Rails. A few things I like in particular:

  • It?s fun. Being able to do Time.now + 5.days or obj.nil? just makes me happy.
  • The community is very helpful and it is easy to find examples/documentation.
  • Convention over configuration means you generally know where to find things when walking into a new large codebase. Especially in comparison to other frameworks that prefer configuration like Django.

37. What do you dislike about Rails?

Machine learning libraries are poorly developed or non-existent.

38. What is your favorite Ruby gem?

One that every Rails developer knows, Devise. It makes setting up something complex like authentication a two-minutes job.

39. What is Spring?

Spring is an application preloader. It keeps the application running in the background so booting is not required any time you run a migration or rake task.

40. What is the asset pipeline?

It?s a framework that prepares JavaScript and CSS for the browser.

41. How have you managed authentication in Rails?

Devise.

42. What is the splat operator?

Splat is used when you don?t want to specify the number of arguments passed to a method in advance. Ruby has two splat operators, the single splat and double splat.

The single splat works as you?d expect:

The double splat is like the single splat but it takes key/values as arguments.

43. What is the difference between include and extend?

Both are mixins that allow injecting code from another module.

But include allows accessing that code via class methods, while extend allows accessing that code via instance methods.

44. What is the difference between load and require?

  • load runs another file, even if it?s already in memory.
  • require will only run another file once, no matter how many times you require it.

45. What is the difference between a class and a module?

  • A class has attributes and methods. You can create an instance of a class.
  • A module is just a collection of methods and constants, which you can mixin with another module or class.

46. What?s a scope?

A scope is ActiveRecord query logic that you can define inside a model and call elsewhere.

Defining a scope can be useful rather than duplicating the same logic in many places in the app.

# an example scopeclass Post scope :active_posts, -> { where(active:true) }end

47. What is the difference between class and instance variables?

Instance variables denoted by @, are associated with an instance of a class. Changing the value of an attribute on one instance has no effect on the variable for another instance.

Class variables denoted by @, are less intuitive. They are shared across all instances of a class. So, changing the variable on one instance affects that variable for all instances.

Notice how the class variable can be updated by any instance of the class.

48. What is the difference between find, find_by, and where in ActiveRecord?

  • find: Takes a single argument and looks up the record where the primary key matches that argument.
  • find_by: Takes key/values and returns the first matching record.
  • where: Takes key/values and returns a collection of matching records. Or an empty collection if there are no matches.

49. What is the difference between select, map, and collect?

All three methods take a block as an argument.

  • select: Is used to grab a subset of a collection. Calling .select! with a bang mutates the original collection.

i = [1,2,3,4,5]i.select {|x| x % 2 == 0}# => [2, 4]

  • map: Performs an action on each element of a collection and outputs an updated collection. Calling .map! with a bang mutates the original collection.

i = [1,2,3,4,5]i.map {|x| x+1}# => [2,3,4,5,6]

  • collect: Is an alias of .map and does the same thing.

50. What are the CRUD verbs and actions in Rails?

verb | action—————GET | indexGET | newPOST | createGET | showGET | editPATCH/PUT | updateDELETE | destroy

51. Define a route for a create action without using ?resources?

  • With resources: resources :photos.
  • Without resources: post ?/photos?, to: ?photos#create?, as: :create_photo.

52. What are the three levels of access control?

  • public: Any object can call this method.
  • protected: Only the class that defined the method and its subclasses can call the method.
  • private: Only the object itself can call this method.

53. How do you use singletons in Ruby?

A singleton is a design pattern that only allows a class to have one instance. This is typically frowned upon in Ruby, but Ruby does come with a module for it.

Conclusion

For interviewees, use this to evaluate your general Ruby on Rails knowledge. While not a comprehensive list, it should cover most questions you?ll be asked in junior or intermediate roles.

For interviewers, this is a good starting point to pick questions from.

23