SlideShare a Scribd company logo
1 of 17
Interview Questions
Ruby
- Sumanth Krishna
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.
Examples
Based 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.
Terminology
Watch out for the specific terms. Usage of right jargon will make the interviewer to understand
you have the experience about it.
Projects
Some 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 & Contributions
Feel free to drop in mail with all your suggestions and feedback. If you are already having
questions with answers do mail me tosumanthkrishna@gmail.com and get the document
updated.
The questions are compiled by browsing through sources on internet and few questions coined
based on the experience.
Legend
Questions in this colour
Context in this colour
Answers in this colour
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
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!
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 themwe 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.
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
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!
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?
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
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 canonly subclass fromone class.Butyou 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?
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 – thesemethods work like public methods within class andlikeprivate 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
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.
 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.
? – 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 gemas 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.
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…
Suggestions & Contributions
Feel free to drop in mail with all your suggestions and feedback. If you are already having
questions with answers do mail me tosumanthkrishna@gmail.com 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

More Related Content

What's hot

Data mining presentation.ppt
Data mining presentation.pptData mining presentation.ppt
Data mining presentation.pptneelamoberoi1030
 
Chapter 1. Introduction
Chapter 1. IntroductionChapter 1. Introduction
Chapter 1. Introductionbutest
 
Building Dynamic Data Pipelines in Azure Data Factory (Microsoft Ignite 2019)
Building Dynamic Data Pipelines in Azure Data Factory (Microsoft Ignite 2019)Building Dynamic Data Pipelines in Azure Data Factory (Microsoft Ignite 2019)
Building Dynamic Data Pipelines in Azure Data Factory (Microsoft Ignite 2019)Cathrine Wilhelmsen
 
Data Quality Patterns in the Cloud with Azure Data Factory
Data Quality Patterns in the Cloud with Azure Data FactoryData Quality Patterns in the Cloud with Azure Data Factory
Data Quality Patterns in the Cloud with Azure Data FactoryMark Kromer
 
Sql vs NoSQL-Presentation
 Sql vs NoSQL-Presentation Sql vs NoSQL-Presentation
Sql vs NoSQL-PresentationShubham Tomar
 
Vector Similarity Search & Indexing Methods
Vector Similarity Search & Indexing MethodsVector Similarity Search & Indexing Methods
Vector Similarity Search & Indexing MethodsKate Shao
 
Pipelines and Data Flows: Introduction to Data Integration in Azure Synapse A...
Pipelines and Data Flows: Introduction to Data Integration in Azure Synapse A...Pipelines and Data Flows: Introduction to Data Integration in Azure Synapse A...
Pipelines and Data Flows: Introduction to Data Integration in Azure Synapse A...Cathrine Wilhelmsen
 
Chap 1 general introduction of information retrieval
Chap 1  general introduction of information retrievalChap 1  general introduction of information retrieval
Chap 1 general introduction of information retrievalMalobe Lottin Cyrille Marcel
 
GeoCass: Geoposicionamiento Inteligente con Apache Cassandra
GeoCass: Geoposicionamiento Inteligente con Apache CassandraGeoCass: Geoposicionamiento Inteligente con Apache Cassandra
GeoCass: Geoposicionamiento Inteligente con Apache CassandraLuis Felipe Tabares Pérez
 
Introduction to Data mining
Introduction to Data miningIntroduction to Data mining
Introduction to Data miningHadi Fadlallah
 
Semantic Web
Semantic WebSemantic Web
Semantic Webhardchiu
 
Module 02 teradata basics
Module 02 teradata basicsModule 02 teradata basics
Module 02 teradata basicsMd. Noor Alam
 
Data Science
Data ScienceData Science
Data ScienceRabin BK
 

What's hot (20)

Data mining presentation.ppt
Data mining presentation.pptData mining presentation.ppt
Data mining presentation.ppt
 
Chapter 1. Introduction
Chapter 1. IntroductionChapter 1. Introduction
Chapter 1. Introduction
 
Building Dynamic Data Pipelines in Azure Data Factory (Microsoft Ignite 2019)
Building Dynamic Data Pipelines in Azure Data Factory (Microsoft Ignite 2019)Building Dynamic Data Pipelines in Azure Data Factory (Microsoft Ignite 2019)
Building Dynamic Data Pipelines in Azure Data Factory (Microsoft Ignite 2019)
 
Introduction to DAX Language
Introduction to DAX LanguageIntroduction to DAX Language
Introduction to DAX Language
 
Data Quality Patterns in the Cloud with Azure Data Factory
Data Quality Patterns in the Cloud with Azure Data FactoryData Quality Patterns in the Cloud with Azure Data Factory
Data Quality Patterns in the Cloud with Azure Data Factory
 
Sql vs NoSQL-Presentation
 Sql vs NoSQL-Presentation Sql vs NoSQL-Presentation
Sql vs NoSQL-Presentation
 
Vector Similarity Search & Indexing Methods
Vector Similarity Search & Indexing MethodsVector Similarity Search & Indexing Methods
Vector Similarity Search & Indexing Methods
 
Pipelines and Data Flows: Introduction to Data Integration in Azure Synapse A...
Pipelines and Data Flows: Introduction to Data Integration in Azure Synapse A...Pipelines and Data Flows: Introduction to Data Integration in Azure Synapse A...
Pipelines and Data Flows: Introduction to Data Integration in Azure Synapse A...
 
Chap 1 general introduction of information retrieval
Chap 1  general introduction of information retrievalChap 1  general introduction of information retrieval
Chap 1 general introduction of information retrieval
 
Spark
SparkSpark
Spark
 
GeoCass: Geoposicionamiento Inteligente con Apache Cassandra
GeoCass: Geoposicionamiento Inteligente con Apache CassandraGeoCass: Geoposicionamiento Inteligente con Apache Cassandra
GeoCass: Geoposicionamiento Inteligente con Apache Cassandra
 
Google cloud Dataflow & Apache Flink
Google cloud Dataflow & Apache FlinkGoogle cloud Dataflow & Apache Flink
Google cloud Dataflow & Apache Flink
 
Introduction to Data mining
Introduction to Data miningIntroduction to Data mining
Introduction to Data mining
 
Big data clustering
Big data clusteringBig data clustering
Big data clustering
 
Semantic Web
Semantic WebSemantic Web
Semantic Web
 
Big Data Modeling
Big Data ModelingBig Data Modeling
Big Data Modeling
 
Data science
Data scienceData science
Data science
 
Module 02 teradata basics
Module 02 teradata basicsModule 02 teradata basics
Module 02 teradata basics
 
Data Science
Data ScienceData Science
Data Science
 
Hadoop vs Apache Spark
Hadoop vs Apache SparkHadoop vs Apache Spark
Hadoop vs Apache Spark
 

Similar to Interview Questions Ruby

Mca2030 object oriented programming – c++
Mca2030  object oriented programming – c++Mca2030  object oriented programming – c++
Mca2030 object oriented programming – c++smumbahelp
 
Java OOPs Concepts.docx
Java OOPs Concepts.docxJava OOPs Concepts.docx
Java OOPs Concepts.docxFredWauyo
 
Learning puppet chapter 2
Learning puppet chapter 2Learning puppet chapter 2
Learning puppet chapter 2Vishal Biyani
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascriptUsman Mehmood
 
Intro Ruby Classes Part I
Intro Ruby Classes Part IIntro Ruby Classes Part I
Intro Ruby Classes Part IJuan Leal
 
Ruby Metaprogramming - OSCON 2008
Ruby Metaprogramming - OSCON 2008Ruby Metaprogramming - OSCON 2008
Ruby Metaprogramming - OSCON 2008Brian Sam-Bodden
 
On the path to become a jr. developer short version
On the path to become a jr. developer short versionOn the path to become a jr. developer short version
On the path to become a jr. developer short versionAntonelo Schoepf
 
Core Java Interview Questions with Answers.pdf
Core Java Interview Questions with Answers.pdfCore Java Interview Questions with Answers.pdf
Core Java Interview Questions with Answers.pdfSudhanshiBakre1
 
Mca2030 object oriented programming – c++
Mca2030  object oriented programming – c++Mca2030  object oriented programming – c++
Mca2030 object oriented programming – c++smumbahelp
 

Similar to Interview Questions Ruby (20)

Mca2030 object oriented programming – c++
Mca2030  object oriented programming – c++Mca2030  object oriented programming – c++
Mca2030 object oriented programming – c++
 
Oop basic concepts
Oop basic conceptsOop basic concepts
Oop basic concepts
 
05 ruby classes
05 ruby classes05 ruby classes
05 ruby classes
 
Java OOPs Concepts.docx
Java OOPs Concepts.docxJava OOPs Concepts.docx
Java OOPs Concepts.docx
 
Ruby object model
Ruby object modelRuby object model
Ruby object model
 
Chapter 8 java
Chapter 8 javaChapter 8 java
Chapter 8 java
 
Learning puppet chapter 2
Learning puppet chapter 2Learning puppet chapter 2
Learning puppet chapter 2
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
 
Patterns of Value
Patterns of ValuePatterns of Value
Patterns of Value
 
JAVA-PPT'S.pdf
JAVA-PPT'S.pdfJAVA-PPT'S.pdf
JAVA-PPT'S.pdf
 
Chapter 7 java
Chapter 7 javaChapter 7 java
Chapter 7 java
 
Intro Ruby Classes Part I
Intro Ruby Classes Part IIntro Ruby Classes Part I
Intro Ruby Classes Part I
 
Object oriented programing
Object oriented programingObject oriented programing
Object oriented programing
 
Suga java training_with_footer
Suga java training_with_footerSuga java training_with_footer
Suga java training_with_footer
 
Ruby Metaprogramming - OSCON 2008
Ruby Metaprogramming - OSCON 2008Ruby Metaprogramming - OSCON 2008
Ruby Metaprogramming - OSCON 2008
 
OOPS ABAP.docx
OOPS ABAP.docxOOPS ABAP.docx
OOPS ABAP.docx
 
On the path to become a jr. developer short version
On the path to become a jr. developer short versionOn the path to become a jr. developer short version
On the path to become a jr. developer short version
 
C#
C#C#
C#
 
Core Java Interview Questions with Answers.pdf
Core Java Interview Questions with Answers.pdfCore Java Interview Questions with Answers.pdf
Core Java Interview Questions with Answers.pdf
 
Mca2030 object oriented programming – c++
Mca2030  object oriented programming – c++Mca2030  object oriented programming – c++
Mca2030 object oriented programming – c++
 

More from Sumanth krishna

Scope demystified - AngularJS
Scope demystified - AngularJSScope demystified - AngularJS
Scope demystified - AngularJSSumanth krishna
 
Services Factory Provider Value Constant - AngularJS
Services Factory Provider Value Constant - AngularJSServices Factory Provider Value Constant - AngularJS
Services Factory Provider Value Constant - AngularJSSumanth krishna
 
Jasmine - A BDD test framework for JavaScript
Jasmine - A BDD test framework for JavaScriptJasmine - A BDD test framework for JavaScript
Jasmine - A BDD test framework for JavaScriptSumanth krishna
 
Ruby on Rails industry trends
Ruby on Rails industry trendsRuby on Rails industry trends
Ruby on Rails industry trendsSumanth krishna
 
Introducing Ruby/MVC/RoR
Introducing Ruby/MVC/RoRIntroducing Ruby/MVC/RoR
Introducing Ruby/MVC/RoRSumanth krishna
 
Watir Presentation Sumanth Krishna. A
Watir Presentation   Sumanth Krishna. AWatir Presentation   Sumanth Krishna. A
Watir Presentation Sumanth Krishna. ASumanth krishna
 
Ro R Based Social Networking Apps Compared
Ro R Based Social Networking Apps ComparedRo R Based Social Networking Apps Compared
Ro R Based Social Networking Apps ComparedSumanth krishna
 
New Rabbit Tortoise Story
New Rabbit   Tortoise StoryNew Rabbit   Tortoise Story
New Rabbit Tortoise StorySumanth krishna
 
RoR relevance to startups Session @ Barcamp5 - Sumanth Krishna
RoR relevance to startups Session @ Barcamp5 - Sumanth KrishnaRoR relevance to startups Session @ Barcamp5 - Sumanth Krishna
RoR relevance to startups Session @ Barcamp5 - Sumanth KrishnaSumanth krishna
 
How Brain Works against in identifying colors?
How Brain Works against in identifying colors?How Brain Works against in identifying colors?
How Brain Works against in identifying colors?Sumanth krishna
 

More from Sumanth krishna (13)

Scope demystified - AngularJS
Scope demystified - AngularJSScope demystified - AngularJS
Scope demystified - AngularJS
 
Services Factory Provider Value Constant - AngularJS
Services Factory Provider Value Constant - AngularJSServices Factory Provider Value Constant - AngularJS
Services Factory Provider Value Constant - AngularJS
 
Jasmine - A BDD test framework for JavaScript
Jasmine - A BDD test framework for JavaScriptJasmine - A BDD test framework for JavaScript
Jasmine - A BDD test framework for JavaScript
 
Ruby on Rails industry trends
Ruby on Rails industry trendsRuby on Rails industry trends
Ruby on Rails industry trends
 
Introducing Ruby/MVC/RoR
Introducing Ruby/MVC/RoRIntroducing Ruby/MVC/RoR
Introducing Ruby/MVC/RoR
 
Watir Presentation Sumanth Krishna. A
Watir Presentation   Sumanth Krishna. AWatir Presentation   Sumanth Krishna. A
Watir Presentation Sumanth Krishna. A
 
Life Pencil And U
Life Pencil And ULife Pencil And U
Life Pencil And U
 
Ro R Based Social Networking Apps Compared
Ro R Based Social Networking Apps ComparedRo R Based Social Networking Apps Compared
Ro R Based Social Networking Apps Compared
 
Put The Glass Down
Put The Glass DownPut The Glass Down
Put The Glass Down
 
New Rabbit Tortoise Story
New Rabbit   Tortoise StoryNew Rabbit   Tortoise Story
New Rabbit Tortoise Story
 
RoR relevance to startups Session @ Barcamp5 - Sumanth Krishna
RoR relevance to startups Session @ Barcamp5 - Sumanth KrishnaRoR relevance to startups Session @ Barcamp5 - Sumanth Krishna
RoR relevance to startups Session @ Barcamp5 - Sumanth Krishna
 
Cookie - story
Cookie - storyCookie - story
Cookie - story
 
How Brain Works against in identifying colors?
How Brain Works against in identifying colors?How Brain Works against in identifying colors?
How Brain Works against in identifying colors?
 

Recently uploaded

Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 

Interview Questions Ruby

  • 2. 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. Examples Based 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. Terminology Watch out for the specific terms. Usage of right jargon will make the interviewer to understand you have the experience about it. Projects Some 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 & Contributions Feel free to drop in mail with all your suggestions and feedback. If you are already having questions with answers do mail me tosumanthkrishna@gmail.com and get the document updated. The questions are compiled by browsing through sources on internet and few questions coined based on the experience.
  • 3. Legend Questions in this colour Context in this colour Answers in this colour
  • 4. 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 are both objects of the class Vehicle, or that apple and pear are both objects of the class Fruit.
  • 5. 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! 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.
  • 6. 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 themwe 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. object.send(method_name, var_1) How to create method(s) dynamically?
  • 7. 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
  • 8. 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!
  • 9. 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?
  • 10. 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
  • 11. 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 canonly subclass fromone class.Butyou 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?
  • 12. 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 – thesemethods work like public methods within class andlikeprivate 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
  • 13. 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.
  • 14.  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.
  • 15. ? – 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 gemas 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:
  • 16. 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…
  • 17. Suggestions & Contributions Feel free to drop in mail with all your suggestions and feedback. If you are already having questions with answers do mail me tosumanthkrishna@gmail.com 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