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)

Beginner

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.

Example 

class Car
        #data
        #functions
end

  • 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
end

 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.

=begin
This is a hello world script. All of these
lines are ignored by the Ruby interpreter.
=end
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
end

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

For Example

class Animal
  def name
    puts "Animal"
  end
end
class Cat < Animal
  def name
    super
  end
end
cat = Cat.new
cat.name
 
# "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. 

Syntax:

objectName=className.new

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

Example

class Car
      def model
        puts "Car model is ABC"
      end
end
obj = Car.new

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

String objects may be created using

 String.new 

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

  Example 

  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

Example

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

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

Example

array1= Array.new
 array2=[]
>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.

Example

h1 = Hash.new 
 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

Regexp.new( ‘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.

Example 

begin
  #here goes the logic
rescue
 # details on how to handle exception
ensure
  # must be executed
end

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.

Example:

if(condition)  
   #executed if condition is true  
else  
   #executed if condition is false  
end  

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.

Example:

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

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.

Syntax

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

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

Example:

unless conditional [then]
   #code
else
   #code 
end

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’

Example

case expression
   #code
when condition1
   #code
when condition2
   #code
end

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.

Example

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

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.

Example

while conditional [do]
   code
end

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.

Example

until conditional [do]
   code
end

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.

Example

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

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.

Example

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

Advanced

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.

Example 

module ModuleName
#statement1
#statement2
end

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.

Example

module Mymodule
def say_hi
  puts "Hi..Hello"
end
end
class Sample
include Mymodule
def say_bye
  puts “Thank you”
end
 end
 obj = Sample.new
 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.

Example

block_name{  
   #statement1  
   #statement2  
}  

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.

Example

a = Proc.new{|x| x = x*10; puts(x) }
a.call(10)

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 “Proc.new” and denoted in this syntax lamda {…..}

Example

b = lambda{|x,y,z| x = y*z; puts(x) }
b.call(2,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. 

Example

class Array
  def reverse
    puts "I am a meta program. I won't do reverse of the array...!"
  end
end
 
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'
else
daytype = 'weekday'
end
return daytype
end
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"
end
irb(main):001:0> message = "welcome"
name="Ruby"
 
 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
=> "WELCOME RUBY"
irb(main):001:0> age = 27
=> 27
 "My age :" + age.to_s
=> "My age :27"
 if age == 27
 puts "Its exact"
 else
 puts "no"
 end
=>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"
 end
=>"age between 20 and 30"
5.times {puts age}
=>27
27
27
27
27
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
end
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')
else
  print('It is not valid data type')
end
irb(main):003:0> a = [22,41,3,"ruby",9.99,100,89]
=> [22, 41, 3, "ruby", 9.99, 100, 89]
a.delete("ruby")
=> "ruby"
a.sort
=> [3, 9.99, 22, 41, 89, 100]
irb(main):001:0> 10.to_s
=> "10"
 "99".to_i.to_f
=> 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"
else
puts "This is  odd Number"
end
end
end
class MixinExample
include Mixin
def say_hi
puts "good day"
end
end
ob = MixinExample.new
ob.even(n)

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

Example :

>ruby -e 'puts "Ruby programming"'

Description

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
Levels