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
  • 27 Question(s)
  • 30 Mins of Read
  • 3352 Reader(s)

Beginner

Ruby files are renamed using rename method and deleted using delete method . 

To rename a file, following syntax is used. 

Syntax: 

File.rename("oldFile.txt", "newFile.txt") 

To delete a file, following syntax is used. 

Syntax: 

File.delete("file.txt") 

================================================================== 

The four types of variables in Ruby are as follows: 

Global variables begin with $ and are accessible from anywhere within the Ruby program regardless of where they are declared—it stands to reason that they must be handled with care. 

Local variables begin with a lowercase letter or an underscore. The scope of a local variable is confined to the code construct within which it is declared. 

Class variables begin with @@ and are shared by all instances of the class that it is defined in. 

Instance variables begin with @ and are similar to class variables except that they are local to a single instance of a class in which they are instantiated. 

In Ruby, methods may either be public, protected, or private. 

Public methods enforce no access control -- they can be called in any scope. 

Protected methods are only accessible within their defining class and its subclasses. 

Private methods can only be accessed and viewed within their defining class . They are only accessible within the context of the current object

The different class libraries used in Ruby are: 

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

Intermediate

Ruby is an open source scripting language and Java is a compiled language. Ruby is mostly focused on simplicity and productivity. Ruby has a simple syntax that is natural to read and easy to write. Ruby is completely free, It is not only free of charge but free to use, copy, modify and distribute. Ruby code is executed only once that is at runtime. Java code is executed twice, compile time and runtime. Both Ruby and Java are Object-Oriented Languages. Ruby is dynamically typed which means type checking is done at runtime whereas Java is statically typed which means type checking is done to compile time. Ruby the code written will be validated during execution by the interpreter. In Ruby, everything is an Object. Ruby's pure Object-Oriented approach can be demonstrated with an example below

5.times { "Hello Ruby" }

You can see how action being applied to a number.

Ruby is seen as a flexible language, as it allows the users to freely alter its code. Ruby blocks are also seen as a source of flexibility. A programmer can attach a closure to a method, altering how that method should act. the closure is called a block. Unlike other Object-Oriented Languages. Ruby features single inheritance only. Ruby features the concept of modules which adds great flexibility to add methods or variables to required classes.

In ruby, we can import with ‘load’ and ‘require’ keyword is used to load packages or modules.

The load method includes the ruby file every time it is being executed.

   load ‘filename.rb’

The commonly used require method includes the ruby file only once.

   require ‘filename’

   require ‘./filename’


For example:

To import file with ‘require’ keyword

Create a file with hello.rb with following code implementation

//--------start code--------------
class Hello
 def print
puts "Hello"
 end
end
//-------end code--------------
Now create a new file with name print_hello.rb with following code implementation
//------start code--------
require './hello'
x = Hello.new
x.print
//----end code--------
Now run the above file from terminal
//-----------------
$ ruby print_hello.rb
Hello
$
//-----------
To import file with ‘load’ keyword
Create a new file with name print_hello2.rb with following code implementation
//------start code--------
load 'hello.rb’
x = Hello.new
x.print
//----end code--------
Now run the above file from terminal
//-----------------
$ ruby print_hello2.rb
Hello
$
//-----------

Ruby has methods which can give you required feature without much of actually implementing it. In the question, the requirement is it prints/defines a range of numbers. So it can to print numbers from 1 to 10, 3 to 10, -3 to 4. In the following example, if you notice “.” is a method which is being applied to an object, say 3. In Ruby, everything is an object and ‘3’ is considered as an object. “10” is a method argument to “.” method. Now when you say “(3..10)” will be a block of code and calling “to_a” method with print an array range from 3 to 10.

The way to define a specific range in ruby is as follows.

//----start code--------
>   (3..10).to_a
=> [3, 4, 5, 6, 7, 8, 9, 10]
>   (-3..4).to_a
=> [-3, -2, -1, 0, 1, 2, 3, 4]
//----end code--------

Ruby has implementations to list range for alphabets. You can say any alphabet say ‘a’, ‘d’ or ‘g’ are objects. “.” is method implementation. When you (‘a’..’h’) will give a block of code and calling ‘to_a’ will generate an array of alphabets starting from ‘a’ and ends at ‘h’.

Example to provide range for alphabets

//----start code--------
>   ('a'..'h').to_a
=> ["a", "b", "c", "d", "e", "f", "g", "h"]
>   ('s'..'v').to_a
=> ["s", "t", "u", "v"]
//----end code--------

Ruby has been a human-readable language. Ruby libraries support almost all the implementations. To print an array in reverse order in Ruby, you can use a library method called ‘reverse’ over an array, which will print the array in reverse order.

The following array is one of the examples to print an array in reverse order with a ‘reverse’ method.

For example:

//----start code----------------
>   ('s'..'v').to_a
=> ["s", "t", "u", "v"]
> ('s'..'v').to_a.reverse
=> ["v", "u", "t", "s"]
>   ('g'..'v').to_a
=> ["g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v"]
>   ('g'..'v').to_a.reverse
=> ["v", "u", "t", "s", "r", "q", "p", "o", "n", "m", "l", "k", "j", "i", "h", "g"]
//----end code----------------

A module in ruby has multiple method implementations, various constants, and different class variables. Modules are defined similarly to a class with a module keyword.

  • Inheritance is not supported by modules
  • Cannot create a subclass of a module.
  • Modules cannot be instantiated.
  • Modules are used as namespaces and as mixins.
  • A class can be a module, but a module can never be a class.
  • A class cannot use mixins like modules.
  • Module name must start with a capital letter.

Syntax:

module Module_name

  # statements to be executed

end

For example:

# Creating a module with name Hello

module Hello

# Prefix with the name of the Module

# module method  

def Hello.welcome

   puts “Hello!! Welcome”

End

end

# calling the methods of the module

Puts Hello.welcome

Hello!! Welcome

Class
Module
Classes are about creating objects.
Modules are more about providing methods that can be used across different classes. You can relate modules with libraries which can be included in classes.
A class can be instantiated.
Modules cannot be instantiated.
A class can create objects.
Modules provide a mixin feature and namespace.
Class has class methods and instance methods.
Module has module methods and instance methods.
Class cannot be included in other class or module.
Module can be included in other modules or classes
Class can be extended with inheritance.
Module is extended with ‘extend’ keyword.

A getter action is a method implementation that gets the value of an instance variable of an object. With the getter method, you can retrieve the value of an instance variable outside the class.
There are multiple ways to have getter action in a class. The most basic implementation is as follows.

For example:

//----start code--------
class Hi
 def initialize(name)
   @name = name
 end
end
obj1 = Hi.new('Bruno)
p obj1.name #=> undefined method `name' for #<Hi:0x007fecd08cb288 @name="Bruno"> (NoMethodError)
//----end code--------

From the above example, the value of obj1.name cannot be retrieved outside Hi class. if you try to retrieve a value of an instance variable outside its class without a getter method, Ruby raises No Method Error.

Defining a getter method within a class will make the value of the name variable within the object.

It is common practice to name a getter method as the instance variable’s name.

//----start code---------
class Hi
 def initialize(name)
   @name = name
 end
 def name
   @name
 end
end
obj1 = Hi.new('Bruno’)
p obj1.name #=> “Bruno”
//----end code--------

Advanced

Both the methods are used to open a file in Ruby 

Difference between both the methods is that File.new method cannot be associated with a block whereas File.open method can be 

File.new method: Using this method a new file can be created for reading, writing or both. 

Syntax: 

f = File.new("fileName.rb") 

File.open method : Using this method a new file object is created. That file object is assigned to a file. 

Syntax: 

#!/usr/bin/ruby 

File.open('about', 'w') do |f| 

f.puts "This is KnowledgeHut" 

f.write "You are reading Ruby interview questions\n" 

f << "Please visit our website.\n" 

end 

freeze method (Object.freeze) is used to prevent an object from being changed. 

water.freeze 

if( water.frozen? ) 

puts "Water object is a frozen object" 

else 

puts "Water object is a normal object" 

end 

In Ruby, the lifecycle of a single thread starts automatically as soon as CPU resources are available. The thread runs the code in the block where it was instantiated and obtains the value of the last expression in that block and returns it upon completion. Threads use up resources but running multiple threads at a time can improve an app’s performance. 

Thread pooling is a technique wherein multiple pre-instantiated reusable threads are left on standby, ready to perform work when needed. 

Thread pooling is best used when there are a large number of short tasks that must be performed. This avoids the overhead of having to create a new thread every time a small task is about to be performed. 

Built-in subclasses of exception are as follows: 

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

The different iterators used in Ruby are: 

  • each iterator 
  • times iterator 
  • upto and down to iterator 
  • step iterator 
  • each_line iterator 

# Add the gem in Gemfile 

gem 'rack', :github => 'rack/rack', :branch => 'master' 

# Execute the below command in your terminal 

$ bundle config local.rack ~/Work/git/rack 

Ruby strings can be compared with three operators: 

  • == operator Returns true or false 
  • eql? operator Returns true or false 
  • casecmp method Returns 0 if matched or 1 if not matched 

Ruby object 

Object is the default root of all Ruby objects. Ruby objects inherit from BasicObject (it is the parent class of all classes in Ruby) which allows creating alternate object hierarchie 

Objects in Ruby are created by calling new method of the class. It is a unique type of method and predefined in the Ruby library. 

Ruby objects are instances of the class. 

objectName = className.new 

We have a class named Circle. Syntax to create an object circle : 

circle = Circle.new("10") 

In Ruby, load and require both are used for loading the available code into the current code. 

require` reads and parses files only once, when they were referenced for the first time. 

`load` reads and parses files every time you call `load`. 

require searches for the library in all the defined search paths and also appends .rb or .so to the file name you enter. It also makes sure that a library is only included once. So if your application requires library A and B and library B requries library A too A would be loaded only once. 

With load you need to add the full name of the library and it gets loaded every time you call load - even if it already is in memory 

nil false nil cannot be a value. false can be a value. nil is returned where there is no predicate. 

in case of a predicate, true or false is returned by a method. nil is not a boolean data type. false is a boolean data type. nil is an object of nilclass. false is an object of falseclass. 

hsh.keys.map(&:to_s).sort_by(&:length) 

or: 

hsh.keys.collect(&:to_s).sort_by { |key| key.length } 

or : 

def key_sort hsh 

hsh.keys.collect(&:to_s).sort { |a, b| a.length <=> b.length } end 

There are multiple ways to do this, but one possible answer is: 

(1..20).inject( [0, 1] ) { | fib | fib << fib.last(2).inject(:+) } 

As you go up the sequence fib, you sum, or inject(:+), the last two elements in the array and add the result to the end of fib. 

Note: inject is an alias of reduce 

A call to super invokes the parent method with the same arguments that were passed to the child method. An error will therefore occur if the arguments passed to the child method don’t match what the parent is expecting. 

A call to super() invokes the parent method without any arguments, as presumably expected. 

‘self ‘ keyword in Ruby is used in different situations depending on the scenario. In other words,
One context of a call to ‘self’ keyword refers to the parent class. Whereas in a different context, ‘self’ keyword may refer to a particular instance of a class.

Class definition self

we can refer to ‘self’ keyword when defining a class in Ruby. We have a Hello class, inside which we’re outputting the value of self:

For example:

//----start code--------
class Hello
   puts "Self is: #{self}"
end
//----end code--------

When calling ‘self’ directly inside the context of a class definition, the self is equivalent to the parent class in which it was defined; Hello, in the above case.

Output is

Self is: Hello  

Class method self

A class method is a method that refers only to that class in all contexts. You can define the class method with ‘Self’ keyword. The following example demonstrates how you can define a class method.

//----start code--------
class Hello
 # Define class variable
 @@name = "John Doe"
 # Getter method
 def self.name
   puts "Self inside class method is: #{self}"
   return @@name
 end
end
puts "Hello class method 'name' is: #{Hello.name}"
//----end code--------

As explained earlier ‘self’ inside a class method definition refers to that parent class object — Hello in this case. We also call Hello.name in the output, to show that our class method getter behaves as expected:

//----start code--------
Self inside a class method is: Hello
Hello class method 'name' is: John Doe  
//----end code--------

Lambda is an anonymous function in ruby, which is also be considered an object in Ruby. You will initialize a lambda and execute it by calling ‘call’ on the initialized variable. The following example will explain how to initialize and call lambda.

//----start code--------
l = lambda { "Hello World" }
puts l.call
> Do or do not
//----end code--------

You can also pass arguments to a Lambda. The following example gives a basic understanding of lambdas with arguments.

//----start code--------
l = lambda do |string|
 if string == "try"
return "There's no such thing"
 else
return "Do or do not."
 end
end
puts l.call("try")
>There's no such thing
//----end code--------

You can define a lambda either with do..end or {}. As per convention followed in Ruby,

{} for single line lambdas and do..end for multiline lambdas.

Ruby is provided with default libraries in the form of classes, which will be accessible after installing ruby in your system. These libraries are referred to as Ruby Standard Library. Some of the libraries need to be invoked explicitly. ‘Date’ class is a library in ruby where you can get most of the actions related to date and make use of these to implement your requirement. You need to load the ‘date’ module in file or IRB or console where you want to print the current day of the week.

The following example is in IRB,

Load ‘date’ class to get the current day of the week in ruby.

For example:

//----start code--------
> load ‘date’
>   Date.today.strftime("%A")
=> "Sunday"
//----end code--------

From the above example, In the first line, we have loaded the ‘date’ library. Now you will have all the required classes and methods available for you in this IRB console. ‘Date’ is the class that we will be using to get the current day of the week. Date.today will give the current day information such as date, month and year. Calling strftime method on the current day to format and get the desired output. In this case, You will use ‘%A’ to get the current day of the week which is ‘Sunday’. There are also many other options to format the date such as get the month in the letter, month in word, year in the letter, year in 4 digits, year in 2 digits, etc

Please refer to the following for more formatting options
Creating a new Time instance

Description

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