Ruby Interview Questions

Prepare better with the best interview questions and answers, and walk away with top interview tips. These interview questions and answers will boost your core interview skills and help you perform better. Be smarter with every interview.

  • 4.6 Rating
  • 50 Question(s)
  • 35 Mins of Read
  • 9874 Reader(s)


Ruby is a dynamic, open source, and an object-oriented programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write. It was designed and developed in 1993 by Yukihiro Matsumoto.  

  • Text processing
  • CGI Programming
  • Network programming
  • GUI programming
  • XML programming
  • Prototyping
  • Programming education

An object is a bundle of variables/data and related methods/functions.

For example: Laptop – Laptop is an object. It has data and functions in it. The hard disk used inside the laptop is data and it is doing lots of functions like calculations, playing movies etc.

Object determines the behaviour of the class.

A class is a collection of objects, in other words, it is a blueprint or a set of instruction to build a specific type of object.


class Car

  • Ruby is an Object Oriented Programming language.
  • Ruby is fast to write as it is an interpreted language.
  • Ruby treats everything as an object.
  • Ruby has simple English like syntax.
  • You will write less code and debugging is simple
  • It saves development time

RubyGems is a package manager for the Ruby programming language that provides a standard format for distributing Ruby programs and libraries, a tool designed to easily manage the installation of gems, and a server for distributing them.

Variable is a symbol or name that holds the value.

There are four types of variables in Ruby:

  • Local variable
  • Class variable
  • Instance variable
  • Global variable

Comments are lines in computer programs that are ignored by compilers and interpreters.

There are two main comments

  • Single line comment
  • Multi line comment

The Ruby single-line comment begins with the # character and ends at the end of the line. Any characters from the # character to the end of the line are completely ignored by the Ruby interpreter.

# This line is ignored by the Ruby interpreter
# This method prints the sum of its arguments
def sum(a,b)
  puts a+b

 A multi-line comment begins with the =begin token and ends with the =end token.

These tokens should start at the beginning of the line and be the only thing on the line. Anything between these two tokens is ignored by the Ruby interpreter.

This is a hello world script. All of these
lines are ignored by the Ruby interpreter.
puts "Hello world!"

A method in Ruby is a set of expressions that returns a value. Other languages sometimes refer to this as a function. A method may be defined as a part of a class or separately.

To use a Ruby method, we need to first define it. It is defined with def and end keyword.

Method name should always start with a lowercase letter.

def method_name
  #some code

Super is used to call the parent classes to initialize method from the child initialize method.

For Example

class Animal
  def name
    puts "Animal"
class Cat < Animal
  def name
cat =
# "Animal"

There are three levels of method access control for classes:

  1.  Public Methods: It can be called by all objects and subclasses of the class in which they are defined in.
  2.  Protected Methods: It can be only accessible to objects within the same class.
  3.  Private Methods: It can be called only in the context of the current object.
  • Ruby data types represent the type of data 
  • Ruby data types are based on the classes
  • Ruby data types don’t need declaration while coding

There are different data types in Ruby:

  • Strings
  • Numbers
  • Hashes
  • Arrays
  • Booleans
  • Symbols

We often use a term object instantiation. It is a synonym for object creation. 


Objects in Ruby are created by calling a new method of the class. 


class Car
      def model
        puts "Car model is ABC"
obj =

A String is an object that represents a set of characters. 

String objects may be created using 

Strings can be defined by enclosing any text with single or double quotes.


  str = "Ruby Scripting"
  str = 'Ruby Scripting'

A number is defined by a series of digits, using a dot as a decimal mark, and optionally an underscore as a thousand separators.

Numeric Data type in Ruby can be divided into 

  • Integer
  • Float

Integer represents whole numbers

Float represents decimal point numbers


a = 2000
a.class => Integer
b = 9.33

Range is a data set with start and end values. In other words, a Range represents an interval ---a set of values with a beginning and an end.

  • Range is a class
  • Ruby supports ranges and allows us to use ranges as Conditions / Sequences / Intervals
  • Always a range is defined with integers but often it can use floating point numbers or characters
  • Example
    r1 = (1..10).to_a
    => [1,2,3,4,5,6,7,8,9,10]
     r2 = ('a'..'z‘)
    => ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o","p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

An array is an ordered list of elements. In other words, an Array is a sequential collection of items in which each item can be indexed.

  • Each element in an array is referred by an index.
  • In Ruby, (unlike many other languages) a single Array can contain items of mixed data types.
  • An Array is created by separating values by commas and enclosing this list with square brackets
  • Array indexing starts at 0

Array can be created in many ways.

  • By  literal constructor []
  • By new class method


>array1 = [1,2,3,4]
>puts array1[0]=>1

A hash is a data structure that stores items by associated keys. In other words, a Hash is a collection of unique keys and their values.

  • It is similar to an Array, except that indexing is done via arbitrary key names, instead of integer index.
  • Entries in a hash are often referred to as key-value pairs. This creates an associative representation of data.

Most commonly, a hash is created using symbols as keys and any data types as values. All key-value pairs in a hash are surrounded by curly braces {} and comma separated.


h1 = 
 h2 = { }
months = {"one" => "January", "two" => "February","three"=>"March"}
>month["one"]= "January"

Regular expressions are handy to filter/find a specific matching pattern in any text. In other words, a regular expression is a sequence of characters that form pattern matching rules and is then applied to a string to look for matches.

In Ruby, there is a class called Regexp with which the expressions can be created.

Regular Expressions can be created by using the constructor or by the following Syntax ‘string pattern' [, options ] )
/string pattern/
%r{string pattern}

 Exceptions are Ruby's way of dealing with unexpected events.

In other words, exceptions help us to capture the failure of executions that disrupts the normal flow of the program’s instructions. Ruby provides a good mechanism to take care of the exceptions.

  • We are writing the code that could raise an exception in a begin/end block. 
  • We can use the rescue method to tell Ruby the types of exceptions.


  #here goes the logic
 # details on how to handle exception
  # must be executed

Built-in subclasses of exception are 

  • StandardError
  • SystenExit
  • SystemStackError
  • fatal - impossible to rescue
  • NoMemoryError
  • ScriptError
  • SecurityError
  • SignalException

Ruby can control the execution of code using Conditional Statements. A conditional Statement takes the result of a test expression and executes a block of code depending on whether the test expression is true or false. If the test expression evaluates to the constant false or nil, the test is false; otherwise, it is true. 

Different types of Conditionals available in Ruby

  • if expression
  • if-elsif-else expression
  • unless expression
  • ternary operator
  • case expression

Ruby if else statement tests the condition. The if- block statement is executed if the condition is true otherwise else block statement is executed.


   #executed if condition is true  
   #executed if condition is false  

Ruby if - elsif statement tests the condition. The if- block statement is executed if the condition is true otherwise elsif block statement is executed.If none of the condition is true else block will be executed.


#executed if condition1is true  
elsif (condition2)  
#executed if condition2 is true  
else (condition3)  
# executed if none is true  

The ternary operator will evaluate an expression and return one value if it's true, and another value if it's false. It's a shorthand of if statement. It is quite popular with single line conditional statement execution.


output= (condition) ? (expressioniftrue) : (expressioniffalse)

The unless expression is the opposite of the if expression. If the value is false the "then" expression is executed. 


unless conditional [then]

The case statement matches one statement with multiple conditions. A case expression is an alternate of if-elsif-else expression. It is similar to a switch statement in other languages. The components of a case statement are ‘case’, ‘when’ and ‘else’


case expression
when condition1
when condition2

Loops are used to execute a set of statements repeatedly based on a condition. It is sometimes necessary to execute a set of statements again and again. Loops and iterators in Ruby are a great way to perform repeated operations on a data set. There are 5 types of loops are available in Ruby

  • For loop
  • While loop
  • Until loop
  • A simple Loop keyword

The for loop consists of for followed by a variable to contain the iteration argument followed by in and the value to iterate over using each.


for variable [, variable ...] in expression [do]

While loop is used to execute a block or segment of code repeatedly until the condition becomes false. A while loop's conditional is separated from code by the reserved word 'do', a newline, backslash \, or a semicolon.


while conditional [do]

Until loop is very similar to while loop. The only difference between while loop and until the loop is that while loop executes set of statements repeatedly until the condition becomes false and until loop executes set of statements repeatedly until the condition becomes true. Until is vice versa of while.


until conditional [do]

The simplest way to create a loop in Ruby is using the loop method. The loop takes a block, which is denoted by { ... } or do ... end. A loop will execute any code within the block until a break statement inside the block, which will force the loop to stop and the execution will continue after the loop.


loop do
  break         # this will cause execution to exit the loop

Iterators are methods that naturally loop over a given set of data and allow you to operate on each element in the collection. Each iterator pulls out each element of a container or an array and assigns to the variable. Using the value of the variable, we can do our desired operation.


[1,2,3].each { |s|
puts s
#=> 1,2,3


Ruby Modules are similar to classes in that they hold a collection of methods, constants, and other module and class definitions. Unlike classes, you cannot create objects based on modules.

With modules you can share methods between classes: Modules can be included in classes, and this makes their methods available on the class.

Modules are defined much like classes are, but the module keyword is used in place of the class keyword.


module ModuleName

The concept of including/loading a module is called ‘mixing in’.Modules are a way of grouping together methods and classes. Ruby will not support multiple inheritances. So, Ruby Modules have another facility called Mixin.


module Mymodule
def say_hi
  puts "Hi..Hello"
class Sample
include Mymodule
def say_bye
  puts “Thank you”
 obj =
 obj.say_hi  #=>Hi..Hello

A Ruby block is a way of grouping statements, and 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.

Ruby Code blocks (called closures in other languages) are definitely one of the coolest features of Ruby and are chunks of code between braces or between do..end that you can associate with method invocations, almost as if they were parameters.



Procs– is a short form of ruby class procedures. Blocks are not objects, but they can be converted into objects of class Proc.

In other words, the instances of these procedures are block objects. To invoke the Proc objects instance method “call” is defined.


a ={|x| x = x*10; puts(x) }

Lamda is also a Proc object, however, it only differs in representation. A lambda is a way to define a block and its parameters with some special syntax.

This is considered as short form of “” and denoted in this syntax lamda {…..}


b = lambda{|x,y,z| x = y*z; puts(x) },5,10)
  • Lambdas check the number of arguments, while procs do not

Procs don’t strictly check the number of arguments you pass in. If you pass the wrong number of arguments into your Lambda, you’ll get an argument error.

  • Lambdas and procs treat the ‘return’ keyword differently

Lamda => ‘return’ inside of a lambda triggers the code right outside of the lambda code.

Proc=>‘return’ inside of a proc triggers the code outside of the method where the proc is being executed

Metaprogramming is the writing of computer programs that write or manipulate other programs (or themselves) as their data, or that do part of the work at compile time that would otherwise be done at runtime. In other word, Metaprogramming is writing code that writes code during runtime to make your life easier.

 As a dynamic language, Ruby gives you the freedom to define methods and even classes during runtime. 


class Array
  def reverse
    puts "I am a meta program. I won't do reverse of the array...!"
a = [1,2,3,4]
puts a.reverse #=> I am a meta program. I won't do reverse of the array...!
def dayIs( aDay )
if aDay == 'Saturday' or aDay == 'Sunday'
daytype = 'weekend'
daytype = 'weekday'
return daytype
day1 = "Monday"
day2 = "Sunday"
print(day1 + " is a " + dayIs( day1 ) + "\n" )
print(day2 + " is a " + dayIs( day2 ) + "\n" )
 score = 100
if  score >= 50 && score < 100
puts "Half century"
elsif score >= 100
puts "Its a century"
elsif score <= 50 && score > 0
puts "Under 50"
elsif score == 0
puts "Its duck"
elsif score != 0
puts "Low score"
irb(main):001:0> message = "welcome"
 message + " " + name
=> "welcome Ruby"
 message + " " + name.upcase
=> "welcome RUBY"
message.capitalize + " " + name.upcase
=> "Welcome RUBY"
 message + " " + name.downcase
=> "welcome ruby"
 message + " " + name.reverse
=> "welcome ybuR"
 message.upcase + " " + name.upcase
irb(main):001:0> age = 27
=> 27
 "My age :" + age.to_s
=> "My age :27"
 if age == 27
 puts "Its exact"
 puts "no"
=>Its exact
 "Next year my age would be " + "#{age+1}"
=> "Next year my age would be 28"
 if age > 20 and age < 30
 puts "age between 20 and 30"
=>"age between 20 and 30"
5.times {puts age}
n = 1000
sum= 0
first = 1
second = 1
puts sum
puts first
puts second
while sum < n do
  sum = first + second
  print sum.to_s + " "
  first = second
  second = sum
input = 'hello'
case (input.class.to_s)
when "String"
  print('It is a string')
when "Fixnum"
  print('It is a fixnum')
when "Float"
 print('It is a float')
when "Bignum"
 print('It is a bignum')
  print('It is not valid data type')
irb(main):003:0> a = [22,41,3,"ruby",9.99,100,89]
=> [22, 41, 3, "ruby", 9.99, 100, 89]
=> "ruby"
=> [3, 9.99, 22, 41, 89, 100]
irb(main):001:0> 10.to_s
=> "10"
=> 99.0
"23 samples".to_i
=> 23
print("Enter the input:")
n = gets()
module Mixin
def even(a)
if a.to_i.even?
puts "It is an even number"
puts "This is  odd Number"
class MixinExample
include Mixin
def say_hi
puts "good day"
ob =

We can use the -e tag against the ruby command.

Example :

>ruby -e 'puts "Ruby programming"'


Ruby is a dynamic, open source programming language which focuses on simplicity and productivity. It is simple in nature but very complex inside. Ruby also has a core class library with a rich and powerful API. It is being inspired by other low level and object-oriented programming languages like Smalltalk, Lisp, and Perl. Ruby uses syntax which is easy for Java programmers and C to learn.

Ruby has become one of the most popular web applications frameworks. Organizations like eBay, Twitter, Slideshare are earning on their investment and the success stories of Ruby has created a huge demand for the Ruby Developers. People with Ruby skills are getting highly paid. As per Payscale, the average pay for Ruby Software Developer/ Programmer is Rs 398,962 per year.

So, if you have finally found your dream job in Ruby but wondering how to crack the 2019 Ruby Interview and what could be the feasible Ruby interview questions, then don’t worry! we have compiled the best interview questions and answers on Ruby. You need to be well prepared with these interview questions and answers on Ruby developer. These Ruby developer interview questions and answers will provide you with in-depth knowledge and help you ace the Ruby developer interview. Ruby programming interview questions here have been designed specially to get acquainted with the nature of questions that you may come across during your interview.

Interview questions on Ruby are prepared by industry experienced trainers. If you wish to learn more on Ruby you can also take up Ruby training which will help you to master.

We hope these Ruby programming interview questions and answers are useful and will help you to get the best job. Be thorough with these Ruby Interview questions for experienced or freshers and take your expertise to the next level.

Read More