Categories

Ruby on Rails Interview Questions and Answers

The web development  market is quite competitive. Knowing the most popular programming languages, frameworks, and technologies is a smart idea. Ruby on Rails (or "Rails") is a Ruby programming language-based open-source web application development framework. It's one of the most widely used Ruby libraries, and it's one of the main reasons developers learn Ruby.

1. What is Ruby on Rails?

1) Ruby is a high-level, interpreted programming language that supports a variety of programming paradigms.

2) Rails, on the other hand, is a framework that can be used to build web applications.

2. What is ORM(Object-Relationship-Model).

In Rails, the ORM or Object Relationship Model indicates that your classes are mapped to the database table, and objects are directly mapped to the table rows. The attributes and relationships of objects in an application may be easily stored and retrieved from a database using ORM, which requires less overall database access code and does not require writing SQL queries directly.

3. What is the difference between String and Symbol?

Strings are any text typed between quote marks ("this is a string," "so is this," "this too!") and symbols are text that starts with a colon (: symbol). Strings and symbols, on the other hand, have diverse functions that make them valuable for different programming tasks.

"Scalar value objects used as identifiers, mapping immutable strings to fixed internal values," according to the Ruby definition. This essentially indicates that symbols are immutable strings.

4. Explain the naming convention in Rails.

Variables: All letters are lowercase, and words are separated by underscores.

Class and Modules: Mixed case, no underscore, each word starts with an uppercase.

Database Table: The database table name should have lowercase letters and underscore between words; all table names should be in the plural form.

Model: Mixed-case, always has singular with the table name.

Controller: Represented in plural form like OrdersController.

5. What is the difference between false and nil in Ruby?

True and false are boolean values in Ruby that signify yes and no, respectively. True is a TrueClass object, and False is a FalseClass object.

Nil is a special value in Ruby that represents the lack of any value. Nil is a NilClass object. Nothing or void is referred to as nil in Ruby.

6. Explain Rails Migration.

A Rails migration is a tool for altering the database schema of an application. Instead of handling SQL scripts, you use a domain-specific language to define database modifications (DSL). Because the code is database-agnostic, you can quickly port your project to a different platform. Migrations can be rolled back and managed alongside your application source code.

7. What is Rails Active Record in Ruby on Rails?

The Object/Relational Mapping (ORM) layer included with Rails is called Active Record. It roughly resembles the conventional ORM model, which goes like this:

1) Tables correspond to classes.

2) Rows correspond to objects, and

3) The columns correspond to the attributes of the objects.

Active Records in Rails provide a connection and interface between relational database tables and Ruby computer code that manipulates database records.

8. What is a Rails Controller?

1) It is in charge of directing external requests to internal processes.

2) It controls caching, which can improve application performance by orders of magnitude.

3) It handles helper modules, which add functionality to view templates without adding code to them.

4) It keeps track of sessions, creating the impression that users are still interacting with our apps. 9. What is Rails Active Record in Ruby on Rails?

9. What do subdirectory app/controllers and app/helpers do?

apps/controller: The controller classes are found in the app/controllers subfolder, which Rails searches for. A user's web request is handled by a controller.

app/helpers: Any helper classes needed to assist the model, view, and controller classes are stored in the app/helpers subdirectory. This keeps the model, view, and controller code clean, simple, and focused.

10. What command can you use to create a controller for the subject?

C:\ruby\library> ruby script/generate controller subject.

11. How to define Instance Variable, Global Variable, and Class Variable in Ruby?

1) Instance Variable in Ruby begins with– @

2) Class variable in Ruby begins with– @@

3) The global variable in Ruby begins with– $

12. Explain Cross-Site Request Forgery (CSRF). How is Rails protected against it?

Cross-Site Request Forgery (CSRF) is a typical online application attack that compromises a victim's authenticated session. This attack entails duping a target into executing unwanted actions on a website to which they have been authenticated.

You must add "protect from forgery" to your ApplicationController to protect against CSRF attacks. Rails will now require a CSRF token in order to complete the request. Every form built using Rails forms builders includes a hidden field called CSRF token.

13. What does garbage collection do in Ruby on Rails?

Garbage collection is a technique for controlling the amount of memory used by computer programs. Garbage collection and other memory management techniques, like reference counting, work by having the language keep track of which objects are in use by a program rather than the developer. This allows the programmer to concentrate on the business logic or other challenge at hand rather than the intricacies of memory allocation and release. This also aids program stability and security, as improper memory management can cause crashes, and memory management bugs account for a major fraction of security bugs.

14. What command is used to create a migration?

C:\ruby\application>ruby script/generate migration table_name

15. Explain how rail implements Ajax?

The way Rails supports Ajax operations is simple and consistent. Different user actions force the browser to display a new web page (like any regular web application) or initiate an Ajax activity after the original web page has been produced and displayed.

1) Some trigger is fired - This could be a user clicking on a button or link, a user changing data on a form or in a field, or just a recurring trigger (based on a timer).

2) The server is contacted by the web client - The XMLHttpRequest JavaScript function transmits data associated with the trigger to a server action handler. The data could be the checkbox ID, the text in an entry field, or the entire form.

3) The server performs the processing- The server-side action handler (Rails controller action) manipulates the data and sends an HTML fragment to the web client.

4) The HTML fragment is received by the client-side JavaScript- The client-side JavaScript which Rails generate automatically is used to alter a specific area of the current page's HTML, usually the content of an
element.

16. What is MVC and how does it work?

The Model-View-Controller (MVC) architectural pattern divides an application into three logical components: model, view, and controller. Each of these components is designed to handle specific parts of application development.

The request initially goes to the controller, who then chooses a suitable view and interacts with the model, who then interacts with your database and sends the response to the controller, who then gives the output parameter to the view based on the response.

17. What are access modifiers in Ruby?

Public: In this, all members are available to everyone to modify.

Private: In this, only functions inside the class can access members.

Protected: In this, the members can only be accessed by functions inside the subclass.

18. What is the role of load and require in Ruby?

1) load( )- We use load to execute code.

2) require( )- We use require to import libraries

19. What is the difference between string and text in Rails?

Both string and text save information of the "string-type" that you can freely write in. The number of characters you can enter in these fields differs between the two. The character limit for a string field is 255 characters, while the character limit for a text field is 30,000 characters.

If you wish to store data like addresses, names, or basic custom data, a string field is an excellent option. When you want to store information from a comment box on a form, or if you're importing a huge block of text, a text area field is an excellent solution

20. Explain the difference between ActiveSupport’s "HashWithIndifferentAccess" and Ruby’s "Hash"?

The "HashWithIndifferentAccess" class treats symbol and string keys as equivalent, whereas Ruby's "Hash" class uses a tighter = = comparison on keys: thus a comparable string key will not get the value for a given symbol key.

21. What is the purpose of the rakefile available in the demo directory in Ruby?

This brief questionnaire is designed to ensure that a developer is familiar with test-driven development. This file may be unfamiliar to a newbie. The rakefile, which is analogous to the makefile in Unix, is used to package and test Rail’s code. The rake utility, which comes with the Ruby installation, makes use of it.

22. What is the difference between observers and callbacks in Ruby on rails?

1) Callback methods in Rails can only be called at specific moments in an object's life cycle, such as validation, creation, updating, deletion, and so on. The rails callback, unlike the rails observers, is only active for a brief time.

2) Rails observers are similar to callbacks, but they're used when a method isn't directly related to the object's life cycle. It can be attached or detached at any time and lives for a longer period of time.

23. What are the limits of Ruby on Rails?

Ruby on Rails is a framework for building MVC-based CRUD web applications. Other programmers may find Rails unusable as a result of this. The following are some of the functionalities that Rails does not support.

1) Databases with foreign keys.

2) Linking to many databases at the same time.

3) Web services for soap.

4) Multiple database servers are connected at the same time.

24. Does Ruby Support Single Inheritance/Multiple Inheritance Or Both?

Ruby only supports single inheritance. It does not support multiple inheritance directly, but it supports something similar- mixins.

25. What are strong parameters? Explain in brief.

Many Rails apps employ Strong Parameters, also known as Strong Params, to strengthen the security of data supplied through forms. Strong parameters allow developers to determine which parameters are accepted and used in the controller. Any superfluous or potentially hazardous params will be ignored and successfully filtered out by allowing only the expected params. This is especially crucial when using Active Model bulk assignments, as numerous params might be provided at the same time.

26. Explain Dynamic Scaffolding ?

At runtime, it generates all of the content and user interface. It allows you to create new, delete, and modify methods for usage in your application. It does not require synchronization with a database.

27. Explain Static Scaffolding

To produce the data with their fields, it takes explicit entry in the command. In static scaffolding, It is not necessary for such generation to occur. It necessitates the migration of the database.

28. Write a function in Ruby to check if the string is a palindrome.

Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast
def palindrome?(str) 
str == str.reverse
end

29. What will be the output of the given code snippet?

x, y, z = 12, 36, 72 
puts "The value of x is #{ x }."
puts "The sum of x and y is #{ x + y }."
puts "The average was #{ (x + y + z)/3 }."

Output:
The value of x is 12.
The sum of x and y is 48.
The average was 40.
 

30. What is the problem with the following controller code? How would you fix it?

x, y, z = 12, 36, 72 
puts "The value of x is #{ x }."
puts "The sum of x and y is #{ x + y }."
puts "The average was #{ (x + y + z)/3 }."

Output:
The value of x is 12.
The sum of x and y is 48.
The average was 40.