Ruby Rails Interview Questions and Answers

Ruby On Rails Interview Questions and Answers

Last updated on 19th Oct 2020, Blog, Interview Question

About author

Sanjay (Sr Technical Architect )

High level Domain Expert in TOP MNCs with 8+ Years of Experience. Also, Handled Around 20+ Projects and Shared his Knowledge by Writing these Blogs for us.

(5.0) | 15632 Ratings 2167

Ruby is being used heavily by many companies all over the world for external and internal use. Many of the web’s popular sites like Twitter, Github, and Yellow Pages are built on rails framework. No wonder, Ruby on Rails has emerged as the most sought skills in web development.

Now that Ruby’s begun its march towards global domination, it’s appearing increasing number of resumes. Sometimes while hiring developers, asking the right questions during the interview is a real challenge. It’s difficult to get a solid read on the candidate’s skill set without looking at the projects they have previously worked on.

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

Ans:

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 ?

Ans:

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 => Fixnum
  • 7.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?

Ans:

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 = 1
  • x = “foo”

4. Tell me about getters and setters in Ruby

Ans:

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?

Ans:

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?

Ans:

$ rake routes

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

7. What is a Gemfile?

Ans:

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?

Ans:

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?

Ans:

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?

Ans:

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?

Ans:

  • 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?

Ans:

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.

13. What are callbacks?

Ans:

“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?

Ans:

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?

Ans:

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?

Ans:

  • 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.

Subscribe For Free Demo

Error: Contact form not found.

  • class Article < < BaseController
  •  has_many :comments, dependent: :destroy
  • end

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

Ans:

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”?

Ans:

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?

Ans:

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

20. What is a PORO?

Ans:

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?

Ans:

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?

Ans:

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?

Ans:

  • 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?

Ans:

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?

Ans:

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?

Ans:

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?

Ans:

  • 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?

Ans:

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?

Ans:

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

30. What is a block in Ruby?

Ans:

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?

Ans:

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?

Ans:

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?

Ans:

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?

Ans:

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.

Course Curriculum

Get In-Depth Knowledge in Ruby on Rails Certification Course

Weekday / Weekend BatchesSee Batch Details

35. What is Active Job?

Ans:

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?

Ans:

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?

Ans:

Machine learning libraries are poorly developed or non-existent.

38. What is your favorite Ruby gem?

Ans:

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

39. What is Spring?

Ans:

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?

Ans:

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

41. How have you managed authentication in Rails?

Ans:

Devise.

42. What is the splat operator?

Ans:

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?

Ans:

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?

Ans:

  • 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?

Ans:

  • 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?

Ans:

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 scope

  • class Post
  •  scope :active_posts, -> { where(active:true) }
  • end

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

Ans:

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.

Ruby on Rails Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

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

Ans:

  • 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?

Ans:

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. Define a route for a create action without using “resources” ?

Ans:

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

51. What are the three levels of access control?

Ans:

  • 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.

52. How do you use singletons in Ruby?

Ans:

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.

Are you looking training with Right Jobs?

Contact Us

Popular Courses