Ruby Interview Questions

21
Interview Questions Ruby

Transcript of Ruby Interview Questions

Page 2: Ruby Interview Questions

Do answer crisply on what asked for.

For almost every question that interviewer asks, be prepared to answer in the order… What? Why? How?

Spend as much time as possible around the topic asked, without switching the topics unless necessary.

ExamplesBased on the concept asked, ensure you quote an example. Pick simplest example without complicating the names, context. Library, Books – a standard example I have picked up to explain the concepts with example. The snippets in the document are around the Books.

TerminologyWatch out for the specific terms. Usage of right jargon will make the interviewer to understand you have the experience about it.

ProjectsSome interviewers might expect how the topic/concept is implemented in projects. Be prepared with set of examples that are simple to quote without revealing much of project internals.

Work in progress

This is an active document and will keep updating as and when time permits.

What Next?Currently working on similar document for Ruby on Rails, Sinatra, Volt, Swift and other JavaScript technologies like AngularJS, ReactJS.

Suggestions & ContributionsFeel free to drop in mail with all your suggestions and feedback. If you are already having questions with answers do mail me [email protected] and get the document updated.

The questions are compiled by browsing through sources on internet and few questions coined based on the experience.

Page 3: Ruby Interview Questions

LegendQuestions in this colour

Context in this colour

Answers in this colour

Page 4: Ruby Interview Questions

In Ruby everything is an Object! Do you agree? Explain in detail.

The most abstract question. Such questions needs to be handled cautiously. This could lead to multiple discussions however, drive the discussion per your comfort. You could try like this…

o Ruby like any object oriented programming language implements Abstraction, Encapsulation, Inheritance, and Polymorphism. Unlike other languages Ruby do not have primitive data types, even integers, strings are considered as objects.

o For example… over irb/console when we hit on

1. 5.class => reveals as Fixnum.

2. Fixnum.superclass => as Integer

3. All the way… goes to show that Object as the parent class.

o In similar lines, even the definition of Array states that collection of “objects”

The safe bet here is that as you ended with Arrays, the question could lead more towards arrays!

What is a class?

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.

o Class – encapsulates the behaviour aka methods/functions, data members aka variables such that on instantiation the object could interact with other objects through the methods.

o Definition is pretty simple with paired keywords class and end. The name should be meaningful and camel case

What is an object?

Another well-known question the expected answer for this varies based on the interviewer!

o Object oriented programming is a paradigm wherein the properties, logical definition of programming is created around objects. The object is the doer can be created by instantiating the classes.

o 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

Page 5: Ruby Interview Questions

are both objects of the class Vehicle, or that apple and pear are both objects of the class Fruit.

o 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 (see question 1).

How would you declare and use a constructor in Ruby?

Pretty straightforward, give the detailed syntax with example

o Constructors are declared using initialize method and get called when you call on a new object to be created.

o Using the example below, calling Book.new acts as a constructor for an object of the class Order.

How does a symbol differ from a string?

Pretty straightforward, talk what symbols are and give example along with merits!

o Short answer: symbols are immutable and reusable, retaining the same object_id.

o Since strings are mutable when a new string instance is created there will be a new object created. This would mean that whenever, a new variable to be labelled a new string is created aka a new object is created. To avoid this we could use symbols which has same object id and reference.

o Give example of how to create symbol - :abc, :’This is also symbol’, in hashes for keys :key1, :key2

o Using all_symbols from ruby console we can find list of symbols used in Ruby and .size gives the count of symbols for the installed version of Ruby.

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

How and when would you declare a Global Variable?

Explain the variable why we need it and how we use it!

Page 6: Ruby Interview Questions

o As per the scope of the variable and ability to access the values of variables we define them. For example, if we need a variable that could be accessed through out the application.

o Global variables are declared with the ‘$’ symbol and can be declared and used anywhere within your program. You should use them sparingly to never.

How would you create getter and setter methods in Ruby?

Though it looks straight forward this could lead to interesting discussion on Meta programming.

o In Ruby variables are private, to access them we use the Setter and Getter methods. They are simple methods/definitions. In case of Ruby these methods are created dynamically using the attr_write, attr_read, attr_accessor methods.

o attr_* methods are themselves wrapper methods. When implemented they would generate the setter and getter methods dynamically using class_eval method. This is called dynamic/meta programming

Explain the use of Meta programming?

Assuming this was asked after the above question still try to give the definition and restress on the same or different example.

Metaprogramming is a paradigm that enables to write code at the run time. Unlike the other processes where one would write, modify or act on data, this paradigm allows one to operate on code itself. This would need inspecting and modifying a program at run time using constructs that are exposed by the programming language.

The classic case of attr_* allows the developers only to identify the attributes and leaving the code generation of required getters and setters to ruby.

How to call send method dynamically? What is send method, what is so special about it?

The ‘send’ is another example for dynamic programming. “send” accepts two arguments one the name of method to be invoked and second the list of variables that need to be passed.

Page 7: Ruby Interview Questions

object.send(method_name, var_1)

How to create method(s) dynamically?

Ruby provides ‘eval’ to execute ruby at the runtime. Using the eval variables, methods, modules, constants are being created at the run time. The ‘send’ is another example for dynamic programming. “send” accepts two arguments one the name of method to be invoked and second the list of variables that need to be passed.

eval(“def #{method_name(arg1)} puts ‘from dynamic method’ end”)

List some of the dynamic methods that (you) have been used?

class_eval instance_eval mod_eval method_missing

class_eval vs instance_eval ?

From the terminology the class_eval would evaluate at class level hence all the evaluated code would be accessible for the instances of a class. instance_eval will create the code that is accessible to the classes. Taking the context of methods instance_eval will create class methods whereas class_eval creates instance methods. The setters and getter methods which are instance methods created by class_eval.

In Ruby, what are instance methods and class methods? How are they different?

Methods consists of logical statements in sequence. Based on the implementation they differ. If methods are to be accessed by objects of a class then they are termed instance methods. If methods are accessed and implemented only by classes then they are called as class methods.

For example while creating new object ”new” method is used over the class which is a class method

book_1 = Book.new

book_2 = Book.new

The instance methods can only be accessed by objects and not classes. Even class methods are also can only be accessed by classes but not objects.

In how many ways the class methods can be created?

Using "self" as the prefix Using class name as the prefix Using "self" insertion syntax followed by methods definition

Page 8: Ruby Interview Questions

Describe the difference between class and instance variables?

Again the variables related query, interviewer may likely to hear word “scope”

Based on the scope of the availability, accessibility of the variables they are classified as local, Instance, class, global.

o Instance variable as the name suggest the scope of the variable will be available/alive as long as the instance available. For say, whenever we instantiate using the instance variables the values can be assigned and accessed across methods that instance operates on.

o Syntactically single @ will be prefixed.

o Class variables that can be accessed by all objects in a class and syntactically double ‘@@’ are prefixed.

o Quote a simple example and illustrate the difference between them.

What is a module? Why Modules? What is the difference between a class and a module?

Explain what module is. Then compare it with class, how similar and how different!

Page 9: Ruby Interview Questions

o A module is a container of methods, classes, modules, variables like class. However, cannot be sub classed or instantiated. They offer namespace to the methods and modules can be included in classes which is called as mix-ins.

o The widely used Comparable, Enumerable in Ruby are some of the examples of modules. They have methods that can be extended by Array, Hash, Set objects

Even in context of Rails, one would notice its usage widely as helpers.

How to define & use modules?

Syntactically modules are defined with keywords “module” followed by “ModuleName” and close the module with “end”.

Once a module defined the methods, variables can be used by objects of class by using keyword “include ModuleName”

After including the module, all the instances of book can implement the formatted name.

Why mix-ins? Do we have any other programming languages using the same or similar concepts? Does Ruby support multiple-inheritance?

Explain about mix-in’s and the need of them in your own words.

Extend the behaviour of objects by including modules is called Mix-in. As Ruby only supports single inheritance, this has been conveniently used to overcome the multiple inheritance concern. There is no limit on number of modules that can be included. As long as the class could satisfy the implementation requirements modules can be included.

Why nested modules?

Page 10: Ruby Interview Questions

Modules offer namespace additionally nested modules help further in organizing them very well. Using scoping resolution operator (“::”) the variables, methods are accessed.

What the difference is between include and extend?

Touch base about the instance and class methods and explain the answer in the same context.

Modules is like a container with methods. Through “include” the methods are available for all the instances of class. Through “extend” the methods are accessible only for classes.

In a class if module is both include and extend then all the methods are available to implement for both instances and class by themselves.

Explain load vs. require vs. include vs. extend?

Each of them are subtly different from one other

load inserts the contents of file

load 'config.rb'

The same file can be loaded more than once, last one sticks

require inserts parsed contents of file

require 'config'

requireing the same file more than once has no effect, first one sticks

include mixes in a module into this class' instances

include FormatHelpers

extend mixes in a module into self, usually to add class methods

Page 11: Ruby Interview Questions

extend FormatHelpers

How does inheritance implemented in Ruby? What is super?

In Ruby the “<” denotes the inheritance between classes.

class Book

include FormatHelper

def published_format

statement -1

statement-2

return “Physical Copy!”

end

end

class eBook < Book

def published_format

super

return “Digital Copy”

end

end

Using ‘super’ keyword the objects from lower/child class can implement methods of parent class, modules.

Both modules and inheritance pretty much do the same “extending behaviour/methods”. In that case d we still need two for one purpose? How do they differ?

Though they are seemingly same they do differ as follows:

You cannot instantiate modules (i.e., no object can be created from a module) Modules are used for namespacing and grouping common methods together.

You can only subclass from one class. But you can mix in as many modules as you'd like.

If it's an "is-a" relationship, choose class inheritance. If it's a "has-a relationship, choose modules. Example: a dog "is an" animal; a dog "has an ability to swim.

Access Modifiers, what are they? How are implemented in Ruby?

Page 12: Ruby Interview Questions

By de-facto unless and until specified all methods are public, this means there are no restriction in accessing the methods written. Private, Protected are other modifiers that exist along with public.

private – when declared, the methods are restricted to be accessed only from other methods defined within the class. By using “private” keyword the methods listed below are all will be declared private.

protected – these methods work like public methods within class and like private methods cannot be accessed outside the class.

Explain some of the looping structures available in Ruby?

Pretty straight forward question nothing specific expectation.

o For loop, While loop, Until Loop.

o Be able to explain situations in which you would use one over another.

What are blocks? Why blocks? Are they objects, functions?

A Ruby block is a way of grouping statements, similar to method definition. However, they are nameless and differ in invocation. Blocks may appear only in the source adjacent to a method call. The block is written starting on the same line as the method call's last parameter (or the closing parenthesis of the parameter list). The code in the block is not executed at the time it is encountered. Through “yield” the block is invocated.

Syntactically, a block is recognized with “{ }” or do….end keywords

To execute the block, the method name from where the execution starts should be same as block name. The blocks will be executed until they are called using yield keyword.

Quote an example of blocks that being used on day to day basis?

In collections Array, Hash, String we use blocks very frequently. For example we deal with loops or iterations

Page 13: Ruby Interview Questions

First, we send the method (collect!) to an Array with a block of code “do … end”.

The code block interacts with a variable used within the method (collect!) and squares it then adds up!

Each element inside the array is now calculated as per the block definition.

What are Procs? What does “call” do?

Blocks are more of functional in nature to make them handy we should be able to create more and more such block objects as and when needed. Proc is a ruby class, whose objects are blocks. They are bound to set of local variables. Once bound, the code may be called in different contexts and still access those variables.

Procs have instance method “call” to invoke these blocks.

What is the difference between lambada and proc? When to use Lambda, Proc?

Proc and Lambda are used to create code blocks. After creating them, we can pass them around our code, just like variables.

Lambda is the short notation for Proc.new, the rest of method invocation remain as is. However they differ in two subtle ways in terms of parameters/variables being passed and the way the last executed statement being returned.

Page 14: Ruby Interview Questions

While invoking call method when more variables have passed the lambda would throw error. Whereas the proc would accept only the required variables and does not throw any error.

While a Proc return will stop a method and return the value provided, lambdas will return their value to the method and let the method continue on to execute the last available statement.

Thus based on the above differences the selection of lambda or proc could be decided.

Difference between “and” and && in Ruby? Difference between “OR” and || in Ruby?

“and” is same as “&&” but with lower precedence.

“OR” is same as “||” but with lower precedence.

Difference between method overloading and method overwriting

The methods would share same name but different number of parameters. When invoked based on the number of parameters the respective method to be picked up. Method Overloading does not require more than one class for overloading.

If the methods have same name and exactly the same number and type of parameters and same return type as a super class then it is overwriting. Method Overriding requires at least two classes for overriding.

Method implementations in Ruby? What is the use of Destructive Method? What is ternary operator?

From the Ruby standard API if observed for Array, Hash, String, Fixnum … we find that few methods implemented with suffixes “!”, “?”.

! – bang operator or Destructive methods. These are used to change the object value permanently by itself. When used the result gets updated in-place of the original value

collection = [8,1,7,3,0,9]

result = collection.sort

puts collection.inspect # [8,1,7,3,0,9]

result = collection.sort!

puts collection.inspect # [0,1,3,7,8,9]

The “sort!” modified the array in-place, hence they are termed as destructive methods.

Page 15: Ruby Interview Questions

? – Ternary operator. These are used to check for the Boolean type. When invoked they return only the true or flase.

How does nil and false differ?

nil is an object for NilClass, whereas false is an object of for FalseClass. false is a boolean data type, where as nil is not. nil cannot be a value, where as a false can be a value.A method returns true or false in case of a predicate, otherwise nil is returned.

What is singleton, when do we need singletons?

Singleton is an interesting pattern. In general for any class, we can create as many instances as possible. And modules cannot be instantiated at all. For example we have to define a various set of properties but would need one and only one instance. “singleton” ensures that once defined a class to be singleton, only one instance can be created.

HOW WILL YOU IMPLEMENT A SINGLETON PATTERN?

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:

Page 16: Ruby Interview Questions

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.

What are Gems and which are some of your favourites?

Interviewer is more interested with your experience with various gems. So start of…

o Gems are Ruby libraries or packages. Through these gems new features and functionality can be added as out of box solutions easily.

Be sure to discuss your list of your favourite gems, why you like them, and any customizations you like to add. While listing group them broadly that way your exposure across multiple aspects of development practices could be understood. Also use this opportunity to highlight any gems you may have published or contributed.

● Developer tools like… rails_footnotes, Benchmarking, Text editors like tinymce, ruby version manager

● Feature add-ons like… devise, activeadmin, paperclip, pagination, omniauth● Documentation and Standards checking like metric_fu, roodi, Rubocop…

Page 17: Ruby Interview Questions

Suggestions & ContributionsFeel free to drop in mail with all your suggestions and feedback. If you are already having questions with answers do mail me [email protected] and get the document updated.

The questions are compiled by browsing through sources on internet and few questions coined based on the experience.

References:

https://www.ruby-lang.org/en/

http://www.gotealeaf.com/books/oo_ruby/read/inheritance

http://dalibornasevic.com/posts/9-ruby-singleton-pattern

http://www.skilledup.com/articles/ruby-on-rails-interview-questions-answers

http://www.stackoverflow.com