Special Offer - Enroll Now and Get 2 Course at ₹25000/- Only Explore Now!

All Courses
Ruby on Rails Interview Questions and Answers

Ruby on Rails Interview Questions and Answers

January 29th, 2019

In case you’re searching for Ruby on Rails Interview Questions and Answers for Experienced or Freshers, you are at the correct place. Gangboard offers Advanced Ruby on Rails Interview Questions and Answers that assist you in splitting your Ruby on Rails Interview and procure dream vocation as Ruby on Rails Developer.

Q1)  Does ruby support multiple inheritance ? How ruby solves multiple inheritance ?

Answer: No. It solves by using mixins. We use include to solve multiple inheritance.
Ex:
class Land
def jump
end
end
class Water
def swim
end
end
class Frog
include Land
include Water
# all methods of Land and Water are available in Frog
end

Q2) How is extend different from include in ruby?

Answer: When methods are extended, we can access them using class variables. When we include the method we can access them using instance variables.

Q3) Is rails rack based application? What is Rack in rails?

Answer: Yes. Rack is a bridge between the application and the server to communicate. The communication happens through env hash.

Q4) What is ORM?

Answer: ORM is object relational mapping.

  • Class in application refers to table names.
  • Object of a class in database refers to a row
  • Attributes in database refers to a columns of the table.

Q5) Explain has_many through association with an real time example ?

Answer: When Patient calls up doctor for an appointment, he gets an Appointment receipt. A doctor may have many patients for an appointment. A patient also may have consulted many doctors with an appointment. So, doctor has_many patients through appointments. patietns has_many doctors through appointments.

Q6) How to add a column in a table in rails ?

Answer: Run rails generate migration —your_file_name—-
def change
add_column :—table_name—, –column_name—, :—column_type—
end

Q7) How rails uses ORM?

Answer: It uses through active record.

Q8) What’s the difference between map and each in ruby?

Answer: Each loops through an array and returns the main array, but map returns the resultant array.

Q9) Explain includes in active record?

Answer: Uses eager loading and optimally used when accessing each member attributes from the associated records. Performs LEFT OUTER JOIN

Q10) Explain joins in active record?

Answer: Uses lazy loading and optimally used when filtering results on condition with associated records.
Performs INNER JOIN

Q11) For avoiding n + 1 queries, should we use includes or joins?

Answer: includes.

Q12) What is nilClass error?

Answer: nil is nothingness in ruby. When calling a method not applicable to nil gives nilClass error.
NoMethodError: undefined method `next’ for nil:NilClass

Q13) How can we avoid nilclass errors?

Answer: By using ‘:try’ for exception handling.

Q14) How does rescue work in ruby?

Answer: rescue is used with begin block. When there’s an error in begin block, control flows through rescue. When there is no begin block, def acts an begin block.
Ex: def get_name
# error occurs here
rescue
# control flow here if error occurs
# render appropriate error messages in rescue block
end

Q15) How render and redirect_to available in controllers and not in models?

Answer: Because render and redirect_to are defined in ActionView::Helpers and accessible from action Controller.

Q16) What is difference between nil? and present? and which is more optimized? nil? checks only if an object is nil? or not. But present? checks if object has some value or not. present? checks value in hash and array too.

Answer: 2.3.1 :017 > a = nil
=> nil
2.3.1 :018 > a.nil?
=> true
2.3.1 :019 > a.present?
=> false
2.3.1 :023 > b = [1, 2, 3] => [1, 2, 3] 2.3.1 :024 > b.nil?
=> false
2.3.1 :025 > b.present?
=> true

Q17) Can we loop into an hash in ruby? Give an example?

Answer: Yes. If h is an hash, then we can loop like this:
h.each do |key, value|
# your code here
end

Q18) What is rvm and what is the command to see all gemsets in rvm?

Answer: rvm is ruby version manager. rvm list is the command to see all gemsets.

Q19) How to embed ruby code into html?

Answer: Need to rename the file with html.erb extension,'<% %>’ will execute ruby code and ‘<%= %>’ will execute ruby code and print the result.

Q20) How to precompile assets in rails?

Answer: We need to add the asset file in ‘/config/initializers/assets.rb’ and re-run the server.

Q21) How to include javascript code in the view using rails?

Answer: using javascript_include_tag.
<%= javascript_include_tag “#{params[:controller]}_#{params[:action]}”, “data-turbolinks-track” => true %>

Q22) How to use strong parameters in rails?

Answer: We need to use ‘require’ and ‘permit’ to allow the required attributes.
Ex: params.require(:student).permit(:name, section, marks)

Q23) Are ‘params’, ‘require’ and ‘permit’ available in model in rails?

Answer: No. These are available in ActionContoller::Parameters, which are accessible from ApplicaitonController and it’s inherited controllers.

Q24) What does rake db:migrate do?

Answer: It executes the migration files staged and commits into the schema of database.

Q25) How to get all route path in the application?

Answer: Run rake routes

Q26) How class and instance variables are defined in controller?

Answer: @@some_variable -> class variable
@some_variable -> instance variable

Q27) Mention some filters used in controllers?

Answer: before_action, before_filter, after_action, around_action

Q28) How to get current datetime in ruby?

Answer: DateTime.now
=> Tue, 25 Dec 2018 17:58:33 +0530

Q29) How to convert IST datetime into USA time.

Answer: By using time_zone(—time_zone_attribute—)
DateTime.now.in_time_zone(‘Central Time (US & Canada)’)
=> Tue, 25 Dec 2018 06:31:54 CST -06:00

Q30) How to convert an datetime object into date object?

Answer: By using ‘to_date’
DateTime.now.to_date
=> Tue, 25 Dec 2018

Q31) What is asynchronous call?

Answer: When the separate thread is evolved from main thread to send a request and not waiting for it’s response is asynchronous call.

Q32) How to configure timezone for the entire application?

Answer: In config/application.rb change:
config.time_zone = ‘Asia/Kolkata’

Q33) When is ActiveRecord::Base.transactions used?

Answer: Placing active record queries in this block ensures all the transactions passes. If anyone fails then all previous database transactions in this transaction block gets rollback.

Q34) How to revert migration files?

Answer: By using rake db:rollback. We can also specify which migration version to rollback.

Q35) Is this below code valid?

Answer: def get_name(first_name, last_name = nil)
puts “#{first_name} #{last_name}”
end
get_name(‘srinidhi’)
Yes. first_name is mandatory whereas last_name is optional. Prints ‘srinidhi’.

Q36) What is CSRF and how rails protects our application?

Answer: Cross site request forgery. protect_from_forgery with: :exception in applicaton controller protects other apps to eavesdrop into our application through API calls. Post requests within our application will hava CSRF token which authenticates each requests.

Q37) What is an CSV?

Answer: CSV is an file with comma separated values, which can be extracted into an excel.

Q38) What is rake task?

Answer: It’s a custom task in ruby excecutable at different application environment. It’s an interface to make custom changes to the application.

Q39) How to get all unique values in an array?

Answer: arr = [1, 2, 3, 3 ,4 ,7, 7] b = arr.uniq
arr.uniq!
The bang(!) assigns the result to arr variable.

Q40) What’s the difference between create and create! in rails?

Answer: create is to add an row in table and rolls back when there is an exception.
create! does the same as create but raises an application.

Q41) When is deep_symbolize_keys in params?

Answer: Which means params having keys with symbol as well as string is accessible.
Ex: params[:name] gives same value as params[‘name’]

Q42) Difference between a symbol and a string?

Answer: String variable can be changed once initiated. But symbol cannot be changed.
2.3.1 :051 > ‘qwe’ + ‘qwe’
=> “qweqwe”
2.3.1 :052 > :qwe + ‘qwe’
NoMethodError: undefined method `+’ for :qwe:Symbol

Q43) How to check element exists in an array? Use include?.

Answer: 2.3.1 :054 > a = [1, 2,  3, 4] => [1, 2, 3, 4] 2.3.1 :055 > a.include?(1)
=> true

Q44) How to access rails sql console?

Answer: rails dbconsole
psql (9.6.2).
gl_lti_production=>

Q45) What is ActionDispatcher?

Answer: Responsible for setting route path for the application. When we add route path in routes.rb, definite path to corresponding controller action is set using ActionDispatcher.
GET, POST, PUT, DELETE are some states.

Q46) Give the hierarchy of ruby method lookup?

Answer: Precedence of ruby methods goes like this:

  1. ‘singleton’ methods
  2. ‘extend’ methods
  3. ‘prepend’ methods
  4. ‘instance’ methods
  5. ‘include’ methods
  6. ‘inherited’ methods

Q47)  Define the polymorphic association in Ruby on Rails?

Answer – Polymorphic association permits an ActiveRecord item to be attached with numerous ActiveRecord objects. It is a communal site for the user so that he can write on videos, photos, links, updating of status. It is not beneficial when you will generate a personal remark such as images_remark, videos_remark, etc.

Q48) What is used to store information in a program of the computer?

Answer – With the help of Variables, the details are saved for mentioning and operating. And have the capacity to give the method for tagging the facts with a detailed name so that the program is easy for understanding the viewers and us. The variable is known as the vessel to manage the details. The tag and saved details are used all over the program.

Q49) Name the uses of Rub on Rails?

Answer – Ruby helps the developers of the structure will build the website and application as it’s conceptual and clarifies the usual uninteresting responsibility. It is known as a programming language and it is used side by side it is a structure of a set of applications, code library to comment for the application the time when you generate a structure then the project is for noticing down the parts of the software.

Q50)  Name the task to write the application of Rail

Answer

  • Explain and copy the domain of application – A domain is considered as the number, a university, to give a dating, to distribute with a book or the storage of the hardware.
  • Select and plan the view publicly of the domain – after deciding for the domain contain student to go in the class, imagine the page of welcome, page of a record, etc.
  • MVC structure of Ruby on Rails – The person who views manages ruler divides the work for use into three parts like model, view, and controller.

Q51)  How to reduce duplicate code?

Answer – With the help of metaprogramming is used in famous structures. And detect the copied code. It enhances the problem of the code in the long run. It helps to open again and change the classes, hold the methods which are not survived and generate on the fly and o generate the Dry code to restrict recurrence.

Q52) Define the rail controller?

Answer– I have known the logical center of the application. It helps to co-relating the communication among the user, model, views.

  • It manages routing the exterior appall to inner act
  • It holds caching to provide the apps and increasing the performances.
  • It can hold the details of the helper to expanse the abilities to notice the templates without increasing the code.

Q53) How to generate a file in a temporary directory?

Answer – With the help of the session, a document is generated on the server in which the principles and changes are saved. The facts are provided on every page on the site at the time of the visit. When the browser is closed by the customer then the session is closed.

Q54)  What are the text files saved on the customer system?

Answer – Cookies are known as the text files and are used to trace the activities. A group of cookies t the browser is mailed by the server text.
For example, his identity card, number, name, age, etc.
To use these details in the future is saved by the browser in the local machine.

Q55) How to design the code by writing a test?

Answer – With the help of TDD to show your purpose for the code. It describes a group of regulations for generating the software for analyzing the cases which are texted earlier. To pass the experiments the code is sufficient. It is a method to depend on repeating a shortened development cycle.

Q56) Describe BDD?

Answer – To write the text for easy understanding for everybody with the help of BBD expands Test-driven development. We can handle the software for organization interest and technical observation. It targets and connects the actions statements by every unit of software beneath the growth.

Q57) What continues tweaking??

Answer – It is considered as the drawback of TDD. And used to construct the data and black-box algorithms component experiments should be accurate. But it is required to convert the algorithms.

Q58) Define Flash messages?

Answer – It is a very easy way of applying one-way interaction. Commonly Flash messages are for informing the customer about the CRUD activities to execute is suitable or not. It is considered as the main part of the session for improving clarity with every appeal. Flash is generated because of disappearing the content after reading it.

Q59) Explain the required parameters?

Answer – These parameters are used when an argument occurred at the time of the method call. When there is no argument at the time of the calling method then it causes an error. We have to face an error which says that the method is provided without any argument.

Q60)  Explain Pluck to hash?

Answer – Pluck is known as the alternate route to choose single or numerous characteristics without loading the comparable records to filter out the chosen characteristics. It reverts an Array of quality principles. Pluck is mixed with a map to generate a hash between the chosen areas and the principles.

Q61) What is Rake?

Answer – Rake is considered the Ruby make and it uses the alternative of the Unix to make the use of Rakefile to construct a record of projects. It is utilized as a management project such as shifting the details by the text load a schema in the details etc.

Q62) Explain callback?

Answer – It the way to make a call in a particular moment of the object life cycle. For example – It can call before and after generating, erasing, updating, validating, storing or deploying from the facts. It is a short process. When running a theme and providing a call-back then thread ends.

Q63) How to change the application details schema?

Answer – With the help of Rail, migration is a tool to convert the details. You can describe the changes in details in a domain-specific language. It is a self-sufficient code to use comfortably to shift the application to a new program. To go back and handle them beside your function source code.

Q64) What is the use of Rail migration?

Answer – The demands are changeable and these changes conduct to database differences. Migration provides the method to change the detailed schema in the application of Rail. Then utilize ruby code with numerous benefits. The application of Rail is kept in the Active record model. Migration saves your details schema differences with application code.

Q65) What is used to issue the error message?

Answer- With the help of the Redirect method. Redirect informs the browser to deliver a new request. It is used at the time of when the customer requires to change the reply to another page or URL.

Q66)  How to create content?

Answer – With the help of Render works in a case only if the detective to set in an accurate manner including the changings are required to furnish. It is the way to create a code of 200 and for providing a page.

Q67) Mention the function of ORM in Ruby on Rails?

Answer – 

  • It is a copy of the category and aid to set the connection between the live models.
  • It permits the category for mapping to the list is available in the database and the items are charted to the rows in the details list.
  • It displays the connection survives between the item and settings.
  • It maintains the details as stated in connection and to act the function stated

Q68) Name the types of various types of associate relationship which survive?

Answer

  • It depends on numerous models that are created in the rail application.
  • To generate the relationship we need command to generate a relationship between the models.
  • If the requirement to display the link in the middle of the various models and can perform by the use of three types of association. As one to one, one to many, many to many.

Q69) What is used to provide the model name?

Answer – With the help of Dynamic Scaffolding includes the function. It contains a physical record in the command. It mechanical creates the whole content and customer attachment at runtime. It needs the introduction of the command to create the facts in the area. It generates in Runtime because dynamic Scaffolding did not need the details to combine. It permits to create the method of new, edit and delete to utilize the application.

Q70) Define CSRF?

Answer – It is a way to criticize the works contains bitter code on the page to enter a web application for the customer to recognize as genuine. If the period of the web application under the time limit then the mugger can accomplish unofficial commands. This is because the customer remains to log in after leaving the site. A black hat site will appeal to log in the site as the customer.

Q71) Which files are in plain text?

Answer – A comma Separated Values files include all numbers and letters and construct the facts included in the table format. To view the details in the particulars from the CVS file. Then you have to notice the file path of the fireplace. You can bring the CVS file in one row in a single time.

Q72) How to fix the issue in a language to restrict async operation?

Answer – 

  • The customer appeals to the server.
  • Then the server files a project for proceeding, the endpoints come back 202is accepted every time the customer appeals to the position of the job.
  • After proceeding the job then the server replies with the outcome of the job.

The replies of the server are not dependent upon the outer means.

Q73) Explain getter in Ruby?

Answer – It is a way to receive a principle of an example variable. You can recover a principle of the example of the variable outside the class and the example of a variable is expressed. The getter method name can be any.

Q74) Define the setter method?

Answer – It is a group of the example of principles. You are not able to provide a principle to the example of principle outer class. Ruby increase NO Method Error if you want to make a group of examples. It occurs at the time when you wish to recover a principle of the example of the variables without using the method of the getter.

Q75) Define the work of setter in Ruby?

Answer – A setter method accepts or renews the principles for an example variable. It is usually an application to get and match the name with the example of the variable of the setter method. mechanically generates a setter method for every condition to give as a comma unrelated symbol by the attr_writter.

Q76) What is Lambdas?

Answer – This function is similar to Procs. Lambdas are for confirming the number of quarrels. It accepts and goes back to an ArgumentError when they are unmatched. It gives tiny go back, it means that at the time of a proc experiences a statement goes back in the implementation. The principle is gone back with the principles of the method that permits for continuing.