Ruby Programming Interview Questions and Answers -Top Answers to Ruby Interview Questions. Learn Ruby programming language with simple and easy examples.
Ruby is a general-purpose, dynamic programming language. Ruby was created by Yukihiro Matsumoto, or "Matz", in Japan in the mid 1990's. Ruby was influenced by Perl, Smalltalk, Eiffel, Ada, and Lisp. It runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. It supports multiple programming paradigms, including functional, object-oriented, and imperative. It also has a dynamic type system and automatic memory management. First version release of Ruby 0.95 in 1995, several stable versions of Ruby were released.  Current version is Ruby 2.5.0 (December 25, 2017).
What is Ruby?
Ruby is a simple and powerful object-oriented, reflective programming language, created by Yukihiro Matsumoto. Ruby is considered similar to Lisp, Smalltalk and Perl. Ruby is designed to be simple, complete, extensible, and portable. You can use Ruby to write servers, experiment with prototypes, and for everyday programming tasks. As a fully-integrated object-oriented language, Ruby scales well.

What are the features of Ruby?
There are some Ruby features:
  • Ruby is a server-side scripting language similar to Python and PERL.
  • Statement delimiters
  • Simple understanding syntax. You can start writing your program from any line and column.
  • It consist Basic OO features (classes, methods, objects, and so on) and Special OO features (mixins, singleton methods, renaming..)
  • Operator overloading and Exception handling
  • Iterators and closures and Garbage collection
  • Dynamic loading (depending on the architecture)
  • High transportability (runs on various Unices, Windows, DOS, OS X, OS/2, Amiga, and so on).
  • It’s up port many GUI tools such as Tcl/Tk, GTK, and OpenGL.
  • It can easily be connected to DB2, MySQL, Oracle, and Sybase.
Why Ruby?
Ruby is known among programmers for a terse, uncluttered syntax that doesn’t require a lot of extra punctuation. Compared to Java, Ruby is streamlined, with less code required to create basic structures such as data fields. Ruby is a modern language that makes it easy to use high-level abstractions such as metaprogramming. In particular, metaprogramming makes it easy to develop a “domain specific language” that customizes Ruby for a particular set of uses (Rails and many gems use this “DSL” capability). Ruby’s key advantage is RubyGems, the package manager that makes it easy to create and share software libraries (gems) that extend Ruby. RubyGems provides a simple system to install gems. Anyone can upload a gem to the central RubyGems website, making the gem immediately available for installation by anyone. The RubyGems website is where you’ll obtain the most recent version of Rails. And it is where you will obtain all the gems that help you build complex websites.

What is RubyGems in Ruby?
RubyGems provides a standard format for distributing ruby programs and libraries. It works as a package manager for the Ruby programming language.

What is Rails?
Rails is a software library that extends the Ruby programming language. David Heinemeier Hansson is its creator. He gave it the name “Ruby on Rails,” though it is often just called “Rails.” Rails is a framework for building websites.

What is an iterator in Ruby?
An iterator is a method which accepts a block or a Proc object. In the source file, the block is placed immediately after the invocation of the method. Iterators are used to produce user-defined control structures especially loops.

What is portability in Ruby?
Ruby language can be ported to many platforms. Ruby programs can be ported to many platforms without any modification to the source code. This feature made the language very useful and highly used by many programmers worldwide. Some of the platforms used are DOS, UNIX, WINDOWS, etc.         

What is the scope of a constant?
A constant defined in a class or module definition can be accessed directly within that class’s or module’s definition. You can directly access the constants in outer classes and modules from within nested classes and modules. You can also directly access constants in super classes and included modules. Apart from these cases, you can access class and module constants using the:: operator, Module Name::CONST1 or Class Name::CONST2.

What is the difference between nil and false in Ruby?
In Ruby, nil and false are the only two objects that evaluate to false in a boolean context. (In other words: they are the only “falsy” values, all other objects are “truthy”.)However, nil and false are instances of different classes (NilClass and FalseClass), and have different behavior elsewhere.We recommend that predicate methods (those whose name ends with a question mark) return true or false. Other methods that need to indicate failure should return nil.

What is the primary difference in these two code things?
// Java
public boolean isEmpty(String s) {
  return s.length() == 0;
# ruby
def empty?(s)
  return s.size == 0
The Java method only accepts Strings as arguments and only returns a boolean while...
The ruby method accepts any Object and could return anything, but in this case will return a boolean if executed without exceptions.

How you define an Instance Variable, Global Variable and Class Variable in Ruby?
  • Instance variable begins with @
  • Class variables begin with @@
  • Global variables begin with $
What is Float, MAX, MIN, NAN and DIG in Ruby?
Float: In Ruby, Float objects represent inexact real numbers using the native architecture's double-precision floating point representation. Float class is used whenever the function changes constantly. It acts as a sub class of numeric. They represent real characters by making use of the native architecture of the double precision floating point.
MAX: Max is used whenever there is a huge need of Float. The largest possible integer in a double-precision floating point number. Usually defaults to 1.7976931348623157e+308.
MIN: The smallest positive integer in a double-precision floating point. Usually defaults to 2.2250738585072014e-308.
NAN: An expression representing a value which is “not a number”.
DIG: Dig is used whenever you want to represent a float in decimal digits. The minimum number of significant decimal digits in a double-precision floating point. Usually defaults to 15.        

What is the difference between   “ ..” and  “...”?
In Ruby, “..”  Includes the right hand side in the range, “...” does not include:
(2..5).to_a   # => [2, 3, 4, 5]
(2...5).to_a # => [2, 3, 4]

How can you declare a block in Ruby?
In Ruby, the code in the block is always enclosed within braces ({}). You can invoke a block by using “yield statement”.

Where are + + and - - operators in Ruby?
Ruby does not have the autoincrement and auto decrement operators. You can use this operators += 1 and -= 1 instead.

What are the common I/O port modes in Ruby?
Common modes in I/O port
a: write-only mode, if file exists it will append the file otherwise a new file will be created for writing only.
a+: read and write mode, if file exists it will append the file otherwise a new file will be created for writing and reading.
r: read-only mode is the default mode starts at beginning of file.
r+: read-write mode, starts at beginning of file.
w: write-only mode, either creates a new file or truncates an existing file for writing.
w+: read-write mode, either creates a new file or truncates an existing file for reading and writing.

What is self in Ruby?
Self in Ruby gives you access to the current object. The object that is receiving the current message. To detail explain: a method call in Ruby is actually the sending of a message to a receiver. When you write obj.meth, you're sending the meth message to the object obj. obj will respond to meth if there is a method body defined for it. And inside that method body, self refers to obj. When I started with Ruby, I learned this pretty quickly, but it wasn't totally apparent when you might actually need to use self. I will outline the two most common use cases I've found for it.

What is the main difference between load and require in Ruby?
Load: load will load and execute a Ruby program (*.rb).
Require: require loads Ruby programs as well, but will also load binary Ruby extension modules (shared libraries or DLLs). In addition, require ensures that a feature is never loaded more than once.

What is the use trap in Ruby?
In Ruby use trap associates code blocks with external events (signals).
trap("PIPE") { raise "SIGPIPE" }

How would you create getter and setter methods in Ruby?
Getters and setters are just methods that are responsible for setting an instance variable (setter), and retrieving the value of an instance variable (getter).
But the more elegant way is to call the attr_accessor method which generates it's for you.
Class Person
  attr_accessor: name
You can also generate just getter or setter individual using attr_reader and attr_writer methods appropriately.

What are levels of method access control for classes in Ruby?
There are three levels of method access control for classes in Ruby:
Public methods: It can be called by all objects and subclasses of the class in which they are defined in.
Protected methods: It’s only accessible to objects within the same class.
Private methods: There are only accessible within the same instance.

In how many ways items can be removed from array in Ruby?
Ruby array elements can be removed in different ways.
  • Shift
  • Delete
  • Pop
  • Uniq
How can I process a file and update its contents in Ruby?
In Ruby, Using the command-line option -i, or built-in variable $-i, you can read a file and replace it.
The code in the preceding question, which added line numbers to a file, is probably best written using this technique:
$ ruby -i -ne 'print "#$.: #$_"' example
If you want to preserve the original file, use -i.bak to create a backup.

What do MatchData#begin and MatchData#end return in Ruby?
They act with $~, and return the start index and the end index of the matched data in the original string.

What is Ruby Hashes?
Hashes (sometimes known as associative arrays, maps, or dictionaries) are similar to arrays in that they are indexed collection of object references. However, while you index arrays with integers, you can index a hash with objects of any types: strings, regular expressions, and so on. When you store a value in a hash, you actually supply two objects - the index (normally called the key) and the value. You can subsequently retrieve the value by indexing the hash with the same key. The values in a hash can be objects of any type.

Can you explain command line executed in Ruby?
Ruby programming language is executed from the command line like most of the scripting languages. Programming and behavior language environment can be controlled from the interpreter itself. Some of the commands which are used are as follows –d, -h, -e prog, -v, -T, -r lib, etc.       

What are class libraries in Ruby language?
Ruby class libraries contain variety of domain such as thread programming, data types, various domains. Following is a list of domains which has relevant class libraries:
GUI: Ruby/Tk and Ruby/Gtk are the classes for GUI programming
XML: UTF-8 text processing regular expression engine make XML programming very handy in ruby.
CGI: There are supporting class library for CGI programming support like, data base interface, eRuby, mod ruby for Apache, text processing classes.
Network programming: Various well-designed sockets are available in ruby for network programming.
Text processing: File, String, Regexp for quick and clean text processing.

How to create a new time instance in Ruby?
A new Time instance can be created with: new. This will use your current system's time. Parts of time like year, month, day, hour, minute, etc can also be passed. While creating a new time instance, you need to pass at least a year. If only year is passed, then time will default to January 1 of that year at 00:00:00 with current system time zone.

Name different methods for IO console in Ruby?
IO Console: The IO console provides different methods to interact with console. The class IO provides following basic methods:
  • IO::console and IO#raw#raw!
  • IO#cooked and IO#cooked!
  • IO#getch and IO#echo=
  • IO#echo? and IO#noecho
  • IO#winsize and IO#winsize=
  • IO#iflush and IO#ioflush
  • IO#oflush
What is sysread method in Ruby?
The sysread method is also used to read the content of a file. With the help of this method you can open a file in any mode.

How do you write to STDOUT in Ruby?
Actually two methods are available:
  • Puts writes with a newline
  • Print writes without a newline
Explain about ruby names?
Classes, variables, methods, constants and modules can be referred by ruby names. When you want to distinguish between various names you can specify that by the first character of the name. Some of the names are used as reserve words which should not be used for any other purpose. A name can be lowercase letter, upper case letter, number, or an underscore, make sure that you follow the name by name characters.

Explain using comments in Ruby?
Comments should be used to give background information or annotate difficult code.there are single line comment and multiline comment
Single-Line Comments:
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.The # character doesn't necessarily have to occur at the beginning of the line; it can occur anywhere.
The following example illustrates a few uses of comments.
 #!/usr/bin/env ruby
 # This line is ignored by the Ruby interpreter
 # This method prints the sum of its arguments
 def sum(a,b)
   puts a+b
 sum(10,20) # Print the sum of 10 and 20
Multi-Line Comments:
Though often forgotten by many Ruby programmers, Ruby does have multi-line comments. 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.
 #!/usr/bin/env ruby
 Between =begin and =end, any number
 of lines may be written. All of these
 lines are ignored by the Ruby interpreter.
 puts "Hello world!"

 What is Ruby code blocks?
 Ruby code blocks form an important part of ruby and are very fun to use. With the help of this feature you can place your code between do-end and you can associate them with method invocations and you can get an impression that they are like parameters. They may appear near to a source of the code and adjacent to a method call. The code is not executed during the program execution but it is executed when the context of its appearance is met or when it enters a method.
Request to Download PDF

Post A Comment: