2016-06-22

Ruby Interview Question answers.

1. How would you declare and use a constructor in Ruby?

Answer: • Constructors are declared via the initialize method and get called when you call on a new object to be created. • Using the code snippet below, calling Order.new acts as a constructor for an object of the class Order.

2. WHAT ARE RUBY GEMS?

Answer: This is a very open ended question and you might be better of to start with the basics first: - A gem is nothing more than a piece of ruby code packaged as a library so that it can be imported and used by others in their programs. - A Ruby gem is therefore simply a library that is written in the ruby programming language. - You can add that you often look for ruby gems on rubygems.org. If you have downloaded any recent gems it might be a good idea to mention those. Some of the popular Ruby gems that your interviewer will likely be faimilar with are: > rails > activerecord > rake > activeadmin - Finally Rubygems is the name of the project that wrote the “gem” ruby library.

3. What is the use of Destructive Method?

Answer: In ruby, we conventionally attach '!' or '?' to the end of certain method names. The exclamation point (!, sometimes pronounced aloud as "bang!") indicates something potentially destructive, that is to say, something that can change the value of what it touches.?chop!?affects a string directly, but?chop?with no exclamation point works on a copy. Here is an illustration of the difference. s1 = "forth" s1.chop!? s2=s1.chop

4. What is the Notation used for denoting class variables in Ruby?

Answer: 1) a constant begins with an uppercase letter and it should not be defined inside a method 2) a local must begin with a lowercase letter or the _ underscore sign 3) a global begins with the $ sign; an uninitialized global has the value of "nil" and also produces a warning. can be reffered anywhere in the program 4) instances begin with the @ sign; an uninitialized instance has the value of "nil" and also produces a warning 5) a class variable begins with double @@ and have to be first initialized before being used in a method definition, otherwise you will get an error if you refer to it without initializin

5. HOW WILL YOU IMPLEMENT AN OBSERVER PATTERN?

Answer: Let’s review first what an observer pattern is all about. The observer pattern (sometimes known as publish/subscribe) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems. You might have used them in other programming languages as listener objects. You use them whenever a button is clicked on the screen and a method gets called automatically. As in the case of the singleton pattern, the observer pattern is also implemented by mixing in a module. In the Ruby implementation, the notifying class mixes in the Observable module, which provides the methods for managing the associated observer objects. And, the observers must implement the update method to receive notifications. Here’s an example. Say you want to send an SMS alert to users if a company stock drops then you can do something like this: require "observer" require "observer" class Ticker # Periodically fetch a stock price include Observable attr_accessor :price def initialize symbol, price @symbol = symbol @price = price end def run lastPrice = nil loop do @price = @price+Random.rand(11) print "Current price: #{price}\n" if @price != lastPrice changed # notify observers lastPrice = @price notify_observers(Time.now, @price) end end end end class Warner def initialize ticker ticker.add_observer(self) # all warners are observers end end class SMSAlert < Warner def update time, price # callback for observer print "--- #{time.to_s}: SMS Alert for price: #{price}\n" end end class EmailAlert < Warner def update time, price # callback for observer print "+++ #{time.to_s}: Email Alert Price changed to #{price}\n" end end Now let’s initialize the classes and run them: ticker = Ticker.new("MSFT", 307) SMSAlert.new(ticker) EmailAlert.new(ticker) ticker.run Current price: 312 --- 2012-02-22 01:26:04 -0800: SMS Alert for price: 312 +++ 2012-02-22 01:26:04 -0800: Email Alert Price changed to 312 Current price: 321 --- 2012-02-22 01:26:04 -0800: SMS Alert for price: 321 +++ 2012-02-22 01:26:04 -0800: Email Alert Price changed to 321 Current price: 323 --- 2012-02-22 01:26:04 -0800: SMS Alert for price: 323 +++ 2012-02-22 01:26:04 -0800: Email Alert Price changed to 323 Current price: 329 --- 2012-02-22 01:26:04 -0800: SMS Alert for price: 329 +++ 2012-02-22 01:26:04 -0800: Email Alert Price changed to 329

6. What is a class?

Answer: • You should easily be able to explain not only what a class is, but how and when you would create a new one as well as what functionality it would provide in the larger context of your program.

7. HOW WILL YOU IMPLEMENT A SINGLETON PATTERN?

Answer: Singleton means single instance. So, the goal of a singleton pattern is to write a class definition but only allow the creation of the single instance of that object. This can be achieved nicely with the singleton gem as shown below: require 'singleton' class Logger include Singleton def initialize @log = File.open("logfile.txt", "a") end def log(msg) @log.puts(msg) end end Adding the singleton as a mixin to the Logger.instance.log('This is just a test message') The code above will create a single instance of Logger and simply put the message in the logger file. Singleton patterns are mostly used for DB instance, Logger instance, etc. —- cases where there should be ONE and only ONE instance of the object that is used. Sometimes you might like to actually hold on to the logger object and use it everywhere you can do so by the following command: logObj = Logger.instance Notice you cannot use the Logger.new to create an object instance because this is a singleton object and therefore calling ‘new’ would fail.

8. HOW CAN YOU IMPLEMENT METHOD OVERLOADING?

Answer: This one’s a tricky question. If you have a background in Java then you must know that method overloading is simply multiple methods with same name but different signatures/parameters. In the case of Ruby method overloading is not supported. However, it does support the overall goal of passing variable number of parameters to the same method. You would implement it like this: class MyClass def initialize(*args) if args.size < 2 || args.size > 3 puts 'This method takes either 2 or 3 arguments' else if args.size == 2 puts 'Found two arguments' else puts 'Found three arguments' end end end end The output can be seen here: MyClass.new([10, 23], 4, 10) Found three arguments MyClass.new([10, 23], [14, 13]) Found two arguments SO: You can get the same effect as method overloading but you just have to manage the number of variables inside your method itself.

9. WHAT IS THE PURPOSE OF YIELD?

Answer: The interpreter essentially invokes a separate piece of code and places it in the location. You might say it is similar to a method calling another method. Let’s understand a little bit of background about where YIELD might be useful first. The Rails framework encourages you to write code that is DRY (Don’t Repeat Yourself). Developers often write common code in a central file and then they write the custom code in the specific files. Let’s say you are building a web application and you want all pages to have a common header, a common footer, the same “Welcome user-name!” message. You can put all this common code in your application.html.erb file. <html> .... common page title .. standard header... <body> ..common page title, <%= YIELD %> ..footer code can go here... </body> </html> The rest of the custom code can go in your specific file. Say the page you are creating is the list of articles. Then in your implementation file you would just write the code for pulling in the articles and the final page displayed to the user would be your custom code which will be placed instead of the <%= YIELD %>code in the application.html.erb file.

10. WHAT IS THE DIFFERENCE BETWEEN A PLUGIN AND A GEM?

Answer: A gem is just ruby code. It is installed on a machine and it’s available for all ruby applications running on that machine. Rails, rake, json, rspec — are all examples of gems. Plugin is also ruby code but it is installed in the application folder and only available for that specific application. Sitemap-generator, etc. In general, since Rails works well with gems you will find that you would be mostly integrating with gem files and not plugins in general. Most developers release their libraries as gems.

11. HOW CAN YOU MIGRATE YOUR DATABASE SCHEMA ONE LEVEL DOWN?

Answer: The rake tool does most of the migrations. It has this nifty syntax to go back one step: rake db:rollback If you want to rollback all the way to the beginning you would use: rake db:reset This would drop the database, recreate the Database and load the current schema into it If you want to rollback multiple steps at the same time you would use: rake db:rollback STEP=3 To rollback all the way and if you are not worried about losing the data then you can drop the database completely with purge like this: rake db:purge

12. HOW CAN YOU SEND A MULTI-PART EMAIL?

Answer: Nowadays most email clients support HTML email, however there are still some old Blackberry phones that prefer emails the ‘ol text way. Therefore it is important to send emails both as HTML and text. This technique is called multi-part emails. The ActionMailer class (included in Rails 3.0) does a great job of sending both text and HTML emails out to the end user at the same time. By default Rails sending an email with plain/text content_type, for example: # app/models/notifier.rb def send_email(email) subject email.subject from email.from recipients email.recipients sent_on Time.now body :email => email end Next let’s update the view in : app/views/notifier/send_email.html.erb Welcome to here: The sent email is a plain text email Date: Thu, 5 Aug 2010 16:38:07 +0800 From: RailsBP To: flyerhzm@gmail.com Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8 Welcome: http://rails-bestpractices.com The link url is just displayed as a plain text because of the email content_type. TEXT/HTML If we want the email clients to display link url as html format, we should change the content_type to text/html in the app/models/notifier.rb file def send_email(email) subject email.subject from email.from recipients email.recipients sent_on Time.now content_type "text/html" body :email => email end Now the sent email is a html formatted email Date: Thu, 5 Aug 2010 17:32:27 +0800 From: RailsBP To: flyerhzm@gmail.com Mime-Version: 1.0 Content-Type: text/html; charset=utf-8 Welcome: http://speechus.com Now the email client can display the link url correctly with html format. The email header looks somewhat like this: Content-Type: multipart/alternative; boundary="----=_NextPart_000_002C_01BFABBF.4A7D6BA0" Content-Type: multipart/alternative tells the e-mail program to expect different parts to follow, separated by a boundary which specified in quotation marks. Actually the boundary could be anything, though hyphens, equal signs, and underscores insure that the e-mail program won't try to display this boundary to the recipient. ------=_NextPart_000_002C_01BFABBF.4A7D6BA0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 8bit

13. HOW CAN YOU IMPLEMENT CACHING IN RAILS?

Answer: Rails offers multiple ways to cache content. Fragment caching is my favorite because it gives you the choice to fragment to pull a portion from the cache and the remaining from a real-time DB call. Say you wanted to show all the orders placed on your website in real time and didn’t want to cache that part of the page, but did want to cache the part of the page which lists all products available, you could use this piece of code: <% Order.find_recent.each do |o| %> <%= o.buyer.name %> bought <%= o.product.name %> <% end %> <% CACHE DO %> All available products: <% Product.all.each do |p| %> <%= link_to p.name, product_url(p) %> <% end %> <% end %> Another technique that works well for static pages is page caching. This technique is often used for home pages and is super fast. class ProductsController < ActionController CACHES_PAGE:index def index @products = Products.all end end

14. WHAT PLUGIN DO YOU USE FOR FULL-TEXT SEARCH?

Answer: Sunspot supports full-text search capability and uses Solr as the back-end search engine to do so. You would include these two plugins in your gem file as shown below: gem 'sunspot_rails' gem 'sunspot_solr'

15. What is the naming conventions for methods that return a boolean result?

Answer: Methods that return a boolean result are typically named with a ending question mark. For example: def active? return true #just always returning true end

16. WHAT IS RESTFUL ROUTING?

Answer: Routing is fun. If you have ever dealt with IIS you will fall in love with RESTful routing. Here’s how it works. Say you want your users to have access to certain pages such as: /photos/new /photos/1/edit /photos/1 And, you want the right controller to get called. And, you want the right view to get rendered. All this is made possible with a single entry in the routes.rb file as shown below: RESOURCES :PHOTOS In Rails, a resourceful route provides a mapping between HTTP verbs and URLs to controller actions. By convention, each action also maps to particular CRUD operations in a database. The single entry in the routing file creates seven different routes in your application.

17. HOW CAN YOU ACHIEVE THE SAME EFFECT AS MULTIPLE INHERITANCE USING RUBY? WHAT IS MIXIN?

Answer: Ruby offers a very neat alternative concept called mixin. Modules can be imported inside other class using mixin. They are then mixed-in with the class in which they are imported. Here’s an example: module Debug def whoAmI? "I am #{self.to_s}" end end class Photo include Debug end ph = Photo.new "I am : #<Photo:0x007f8ea218b270>" As you can see above the class Debug and it’s method “whoamI?” were mixed-in (added) with the class Photo. That’s why you can now create an instance of the Photo class and call the whoAmI? method. ph.whoAmI? => "I am : #<Phonograph:0x007f8ea218b270>"

18. WHAT IS RAKE?

Answer: Rake is a popular ruby gem that makes the job of running tasks simpler. Rake is most often used for DB tasks, but it can be used for m The common DB commands are: rake db:migrate rake db:reset You can use cron to schedule rake tasks. Sometimes you would create a dataloader.rake file and put it in the lib/tasks folder so that it can be used to populate the database on startup.

19. HOW DO YOU DEFINE GLOBAL VARIABLES?

Answer: Global variables are defined using single $ symbol. $foo = 5 It can be declared anywhere and used anywhere. Generally you shouldn’t declare too many global variables but sometimes it makes sense to do so. One nice feature of a global variable is that it can be used to trigger a procedure if it’s value changes. trace_var :$foo, proc{puts "$foo is now #{$foo}"} This set the tracking and the procedure is called whenever the value of $foo changes. $foo=7 $foo is now 7 => 7

20. WHAT IS A FILTER? WHEN IT IS CALLED?

Answer: Filters are methods that are called either before/after a controller action is called. Say a user requests a controller action such as userdashboard/index In such a case a filter can be setup so that the UserDashboard/index page is only accessible to loggedin users by adding the following lines towards the beginning of the page: class UserDashboardController < ApplicationController before_filter :confirm_logged_in, :except => [:login, :attempt_login, :logout] def index .... end def login .... end def attempt_login .... end def logout .... end end In the code above the condition “confirm_logged_in” is checked before all actions, except login, logout & attempt_login. After filters (after_filter) are not used too much but they have the effect of executing some code after a particular action has completed. Think of them like triggers that get executed automatically — just like a database trigger.

21. WHAT DO CONTROLLERS DO IN RAILS?

Answer: Once a request comes into the Rails stack, it goes to the routes table to determine which controller and action should be called. Once a controller action is determined the request is routed to the controller and it does the needed processing by connecting with the DB if needed and then it sends control to the View to render the output. So, really the flow for Rails goes somewhat like this: Customer-> Routes-> Controller -> Model(DB) -> Controller -> View -> Customer

22. HOW CAN YOU CREATE SETTER AND GETTER METHODS IN RUBY?

Answer: The setter and getter methods can be created manually by the developer or it can be auto-generated by Ruby using the attr_accessor method specifier. class Animal attr_accessor :name, :age end anim = Animal.new => #<Animal:0x007f8ea20841d8> anim.age = 3 => 3 anim.name = "Steve" => "Steve" puts anim.name, anim.age Steve 3 Of course you can achieve the same result by implementing all the setter and getter methods like this as well: class Animal def name # this is the getter method @name end def name=(name) # this is the setter method @name = name end #...same for age... end

23. HOW CAN YOU DYNAMICALLY DEFINE A METHOD BODY?

Answer: An instance method can be defined dynamically with Module#define_method(name, body), where name is the method’s name given as a Symbol, and body is its body given as a Proc, Method, UnboundMethod, or block literal. This allows methods to be defined at runtime, in contrast to def which requires the method name and body to appear literally in the source code. class Conjure def self.conjure(name, lamb) define_method(name, lamb) end end # Define a new instance method with a lambda as its body Conjure.conjure(:glark, ->{ (3..5).to_a * 2 }) Conjure.new.glark #=> [3, 4, 5, 3, 4, 5] Module#define_method is a private method so must be called from within the class the method is being defined on. Alternatively, it can be invoked inside class_eval like so: Array.class_eval do define_method(:second, ->{ self.[](1) }) end [3, 4, 5].second #=> 4 Kernel#define_singleton_method is called with the same arguments as Module#define_method to define a singleton method on the receiver. File.define_singleton_method(:match) do |file, pattern| File.read(file).match(pattern) end File.match('/etc/passwd',/root/) #=> #<MatchData "root">

24. Explain how (almost) everything is an object in Ruby:

Answer: • This is a simple question based on complex concept. Here’s your chance to show off your theoretical knowledge and demonstrate that you can have an in depth conversation on class hierarchies, inheritance, methods, encapsulation, polymorphism, and more. • Explaining this could take an hour or a few minutes – there’s no single correct answer here, save from being able to demonstrate your familiarity with OOP concepts.

25. HOW DO YOU DEFINE INSTANCE VARIABLES?

Answer: Instance variables are defined using single @ symbol. @foo = "Hello" Within a class they can be declared as below: class Animal attr_accessor :name, :age end Next you can query an object instance to find which instance variables it has. anim = Animal.new anim.instance_variables => [ ] anim.name="John" anim.age = 3 => [:@age, :@name] In the above case we did not put the @ symbol before the instance variables but it is implied.

26. WHAT IS A RANGE?

Answer: Range is a great way to declare continuous variables. You should use it to declare arrays and other types of collections. range1 = (1..4).to_a => [1, 2, 3, 4] puts range1 1 2 3 4 You can also create strings in this format and it fills in the interim values automatically. range2 = ('bar'..'bat').to_a puts range2 bar bas bat Since the end result of using range is an array you can also iterate over it just like any other array. range2.each do |str| puts "In Loop #{str}" end This produces the result as shown below: In Loop bar In Loop bas In Loop bat

27. HOW CAN YOU UPLOAD A FILE TO A SERVER?

Answer: Paperclip is the best solution to manage file uploads to a server. It can also help you with multiple file uploads and associate it with ActiveRecord. There are also good examples online that show how you can make rotating sliders with the paperclip images. Another nice solution is using carrier_wave gem. The nice thing about carrier_wave is that it has good documentation on how to integrate with S3, Google & Rackspace for file storage. You can achieve the same file storage capability with Paperclip as well though.

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

Answer: • The straightforward answer: A module cannot be subclassed or instantiated, and modules can implement mixins. • Be prepared to discuss what this actually means in real life, and when you would use a module vs. a class and why.

29. IS RAILS SCALABLE?

Answer: Yes Rails gives you complete freedom to use all traditional means of scaling an application. Things like memcached, caching full pages, caching fragments are all supported. You can use any standard CDN to serve your media and static content as well. Database scaling using sharding is supported. Finally heroku makes your life easier by giving you the flexibility to scale up/down based on your need. Mostly websites have a peak time during which you need more servers and then there is a sleep time. Heroku makes that on-demand scaling process simpler. Companies such as HireFireApp.com makes the autoscale process easier.

30. What is an object?

Answer: • Textbook answer here is that an object is an instance of a class and has state, behavior, and identity. In a plain text example, you can say that a truck and a car are both objects of the class Vehicle, or that apple and pear are both objects of the class Fruit. • You should be able to explain in detail how object structure and behavior relate to their common class, and why this is so important in Ruby.

31. WHAT IS A SWEEPER?

Answer: Sometimes you want to have control over how often and when the cache expires. Sometimes it is a good idea to have the system determine that on a logical basis. Say you have a list of product on your site and you want to reload the cache each time a new product is added/updated/deleted, then you can achieve this by using the sweeper. class ProductSweeper < ActionController::Caching::Sweeper OBSERVE PRODUCT# This sweeper is going to keep an eye on the Product model # If our sweeper detects that a Product was created call this def after_create(product) expire_cache_for(product) end # If our sweeper detects that a Product was updated call this def after_update(product) expire_cache_for(product) end # If our sweeper detects that a Product was deleted call this def after_destroy(product) expire_cache_for(product) end private def expire_cache_for(product) # Expire the index page now that we added a new product expire_page(:controller => 'products', :action => 'index') # Expire a fragment expire_fragment('all_available_products') end end

32. How does a symbol differ from a string?

Answer: • Short answer: symbols are immutable and reusable, retaining the same object_id. • Be prepared to discuss the benefits of using symbols vs. strings, the effect on memory usage, and in which situations you would use one over the other. Symbols and string are used interchangeably by various developers and their usage within gems can be confusing at times. You can think of Symbols as faster & immutable strings. Once a string is used up it is marked for cleaning by the garbage collector but it is not cleaned up immediately and it cannot be reused. Symbols live for the duration of the session. You might say that this leads to increased memory usage however by keeping the symbol alive a bit longer it can be reused again.

33. WHAT IS THE DIFFERENCE BETWEEN ?&&?, ?AND? AND ?&? OPERATORS?

Answer: The ‘&&’ and ‘and’ are both logical and statements. They ‘&&’ operator has higher precedence though. Here’s an example of illustrate this in more detail: foo = 3 bar = nil a = foo and bar # => nil a # => 3 a = foo && bar # => nil a # => nil Notice how the statement ‘a = foo and bar’ actually behaves like ‘(a = foo) and bar’

34. WHAT IS THE PURPOSE OF LAYOUTS?

Answer: Layouts are partial ruby/html files that are used to render the content pages. There are placed in the folder: app/views/layouts Items that you would typically put in this folder are things like headers/footers, navigation elements, etc. Here’s a sample layout file: /app/views/layout/application.html.erb <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Learning System | <%= @page_title || 'Admin Area' %></title> <meta name="author" content="Anil Punjabi"> <%= stylesheet_link_tag('public', 'admin', :media => 'all') %> <%= javascript_include_tag('application') %> </head> <body> <div id="header"> <h1>Learning System</h1> </div> <div id="main"> <% if !flash[:notice].blank? %> <div class="notice"> <%= flash[:notice] %> </div> <% end %> <div id="content"> <%= yield %> </div> </div> <div id="footer"> <p id="copyright">© / Anil Punjabi</p> </div> </body> </html> Say you are trying to access the page as shown below: http://mysite.com/page/index Then the contents of the index.html.erb would be placed above in the section shown under <% yield %> above and sent back to the user.

35. WHAT ARE CLASS VARIABLES? HOW DO YOU DEFINE THEM?

Answer: Class variables are created using the @@ prefix to denote the variable as class level. It works just like any other variable, however in the case of inheritance it works more like a static variable that is accessed across all variable instances. Another example can be found here: class DemoClass @@my_var = nil def initialize @@my_var = "hello world" end def my_var puts @@my_var end end class Demo2Class < DemoClass def initialize @@my_var = "goodbye world" end end demo1 = DemoClass.new demo1.my_var demo2 = Demo2Class.new demo2.my_var demo1.my_var The output would be as shown below: hello world goodbye world goodbye world This may appear strange at first, but really all it shows is that the variable my_var is shared across both object instances.

36. What is the use of super in Ruby Rails?

Answer: Ruby uses the super keyword to call the superclass implementation of the current method. .Within the body of a method, calls to super acts just like a call to that original method. .The search for a method body starts in the superclass of the object that was found to contain the original method. def url=(addr) super (addr.blank? || addr.starts_with?('http')) ? addr : http://#{addr} end

Show more