Ruby Interview Questions And Answers

1)What is Ruby programming language?

Ans)Ruby is a dynamic, reflective, general purpose, open source programming language that focuses on simplicity and productivity. Ruby has a mixed features of Perl, small talk, Eiffel, Ada and Lisp. Ruby was designed to create a new language which makes a balance with the functionality of Imperative languages.

2)Who is the developer of Ruby?

Ans)Ruby is designed and developed by Yukihiro "martz" Matsumoto in mid 1990 in Japan.

3)Why Ruby is known as a language of flexibility?

Ans)Ruby is known as a language of flexibility because it facilitates its author to alter the programming elements. Some specific parts of the language can be removed or redefined. Ruby does not restrict the user. For example, to add two numbers, Ruby allows to use + sign or the word 'plus'. This alteration can be done with Ruby's built-in class Numeric.

4)Write the command to get installed Ruby version in your system.

Ans)ruby -v

5)What are class libraries in Ruby?

Ans)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:

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

  • 6)What is RubyGems in Ruby programming language?

    Ans) RubyGems provides a standard format for distributing ruby programs and libraries. It works as a package manager for the Ruby programming language. RubyGems is now a part of the standard library from Ruby version 1.9.

    7)What is the use of load and require in Ruby?

    Ans)In Ruby, load and require both are used for loading the available code into the current code. In cases where loading the code required every time when changed or every times someone hits the URL, it is suggested to use 'load'. It case of autoload, it is suggested to use 'require'.

    8)Explain Ruby if-else statement.

    Ans) The Ruby if-else statement is used to test condition. There are various types of statement in Ruby.

  • if statement
  • if-else statement
  • if-else-if (elsif) statement
  • ternary statement

  • 9)Explain case statement in Ruby?

    Ans) In Ruby, we use 'case' instead of 'switch' and 'when' instead of 'case'. The case statement matches one statement with multiple conditions just like a switch statement in other languages.

    10) Explain for loop in Ruby.

    Ans)Ruby for loop iterates over a specific range of numbers. Hence, for loop is used if a program has fixed number of itrerations. Ruby for loop will execute once for each element in expression.

    11)Explain break statement in Ruby?

    Ans) Ruby break statement is used to terminate a loop. It is mostly used in while loop where value is printed till the condition is true.

    12)Explain redo statement in Ruby?

    Ans)Ruby redo statement is used to repeat the current iteration of the loop. The redo statement is executed without evaluating loop's condition.

    13) Explain Ruby object?

    Ans)Object is the default root of all Ruby objects. Ruby objects inherit from BasicObject which allows creating alternate object hierarchies.

    14) In how many ways a block is written in Ruby.

    Ans)A block is written in two ways: Multi-line between do and end Inline between braces {} Both are same and have the same functionality. For more information: Click here syntax: block_name{ statement1 statement2 .......... }

    15) Explain ampersand parameter (&block) in Ruby?

    Ans) The &block is a way to pass a reference (instead of a local variable) to the block to a method. Here, block word after the & is just a name for the reference, any other name can be used instead of this.

    16)Explain Ruby module?

    Ans) Ruby module is a collection of methods and constants. A module method may be instance method or module method. They are similar to classes as they hold a collection of methods, class definitions, constants and other modules. They are defined like classes. Objects or subclasses can not be created using modules. There is no module hierarchy of inheritance. Modules basically serve two purposes: They act as namespace. They prevent the name clashes. They allow the mixin facility to share functionality between classes. Syntax: module ModuleName statement1 statement2 ........... end

    17) Explain module mixins in Ruby?

    Ans)Ruby doesn't support multiple inheritance. Modules eliminate the need of multiple inheritance using mixin in Ruby. A module doesn't have instances because it is not a class. However, a module can be included within a class. When you include a module within a class, the class will have access to the methods of the module.

    18) How to access Ruby strings elements in an application?

    Ans) You can access Ruby string elements in different parts with the help of square brackets []. Within square brackets write the index or string.

    19) How to write multiline string in Ruby?

    Ans) Writing multiline string is very simple in Ruby language. We will show three ways to print multiline string. String can be written within double quotes. The % character is used and string is enclosed within / character. In heredoc syntax, we use << and string is enclosed within word STRING.

    20) What is the use of global variable $ in Ruby?

    Ans)The global variable is declared in Ruby that you can access it anywhere within the application because it has full scope in the application. The global variables are used in Ruby with $ prepend.

    21)What is concatenating string in Ruby. In how many ways you can create a concatenating string.

    Ans)Ruby concatenating string implies creating one string from multiple strings. You can join more than one string to form a single string by concatenating them. There are four ways to concatenate Ruby strings into single string:

  • Using plus sign in between strings.
  • Using a single space in between strings.
  • Using << sign in between strings.
  • Using concat method in between strings.

  • 22)What are freezing string in Ruby?

    Ans) In most programming languages strings are immutable. It means that an existing string can't be modified, only a new string can be created out of them. In Ruby, by default strings are not immutable. To make them immutable, freeze method can be used.

    23)In how many ways you can compare Ruby string?

    Ans)Ruby strings can be compared with three operators:

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

  • 24)What are Ruby arrays and how they can be created?

    Ans)Ruby arrays are ordered collections of objects. They can hold objects like integer, number, hash, string, symbol or any other array. Its indexing starts with 0. The negative index starts with -1 from the end of the array. For example, -1 indicates last element of the array and 0 indicates first element of the array. A Ruby array is created in many ways.

  • Using literal constructor []
  • Using new class method

  • 25) How to access Ruby array elements? How many methods are used to access Ruby elements.?

    Ans) Ruby array elements can be accessed using #[] method. You can pass one or more than one arguments or even a range of arguments. Syntax: #[] method Methods used to access Ruby elements: at method slice method fetch method first and last method take method drop method
    26) What are class libraries in Ruby?

    Ans)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: Text processing CGI Programming Network programming GUI programming XML programming

    27)In how many ways items can be added in an array in Ruby?

    Ans)Ruby array elements can be added in different ways. push or << unshift insert

    28) In how many ways items can be removed from array in Ruby?

    Ans) Ruby array elements can be removed in different ways. pop shift delete uniq.

    29) Explain Ruby hashes.

    Ans)A Ruby hash is a collection of unique keys and their values. They are similar to arrays but array use integer as an index and hash use any object type. They are also called associative arrays, dictionaries or maps. If a hash is accessed with a key that does not exist, the method will return nil.

    30) How to create a new time instance in Ruby?

    Ans) 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.

    31)What are Ruby iterators?

    Ans) Iterator is a concept used in object-oriented language. Iteration means doing one thing many times like a loop. The loop method is the simplest iterator. They return all the elements from a collection, one after the other. Arrays and hashes come in the category of collection.

    32) How to open a file in Ruby?

    Ans) A Ruby file can be created using different methods for reading, writing or both. There are two methods to open a file in Ruby. method : Using this method a new file can be created for reading, writing or both. method : Using this method a new file object is created. That file object is assigned to a file. Difference between both the methods is that method can be associated with a block while method can't. Syntax: f ="fileName.rb") Or,"fileName.rb", "mode") do |f|

    33)How to read a file in Ruby?

    Ans)There are three different methods to read a file. To return a single line, following syntax is used. Syntax: f.gets code... To return the whole file after the current position, following syntax is used. Syntax: f.rea code... To return file as an array of lines, following syntax is used. Syntax: f.readlines [code...]

    34)What is sysread method in Ruby?

    Ans) 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.

    35) How will you rename and delete a file in Ruby?

    Ans) Ruby files are renamed using rename method and deleted using delete mehtod. To rename a file, following syntax is used. Syntax: File.rename("olderName.txt", "newName.txt") To delete a file, following syntax is used. Syntax: File.delete("filename.txt")

    36)How to check whether a directory exist or not in Ruby?

    Ans) To check whether a directory exists or not exists? Method is used. Syntax: puts Dir.exists? "dirName"

    37)Explain Ruby exceptions.

    Ans)Ruby exception is an object, an instance of the class Exception or descendent of that class. When something goes wrong, Ruby program throws an exceptional behavior. By default Ruby program terminates on throwing an exception.

    38)How an exception is handled in Ruby?

    Ans) To handle exception, the code that raises exception is enclosed within begin-end block. Using rescue clauses we can state type of exceptions we want to handle.

    39) Explain raise statement in Ruby?

    Ans) The raise statement is used to raise an exception. Syntax: raise Or, raise "Error Message" Or, raise ExceptionType, "Error Message" Or, raise ExceptionType, "Error Message" condition

    40)Explain the use of ensure statement in Ruby?

    Ans)There is an ensure clause which guarantees some processing at the end of code. The ensure block always run whether an exception is raised or not. It is placed after last rescue clause and will always executed as the block terminates. The ensure block will run at any case whether an exception arises, exception is rescued or code is terminated by uncaught exception.

    41) Explain what is ORM (Object-Relationship-Model) in Rails?

    Ans)ORM or Object Relationship Model in Rails indicate that your classes are mapped to the table in the database, and objects are directly mapped to the rows in the table.

    42)Mention what the difference is between false and nil in Ruby?

    Ans)In Ruby False indicates a Boolean datatype, while Nil is not a data type, it have an object_id 4.

    43) Explain what is the role of sub-directory app/controllers and app/helpers?

    Ans) App/controllers: A web request from the user is handled by the Controller. The controller sub-directory is where Rails looks to find controller classes
    App/helpers: The helper’s sub-directory holds any helper classes used to assist the view, model and controller classes.

    44) Mention what is Rails Migration?

    Ans) Rails Migration enables Ruby to make changes to the database schema, making it possible to use a version control system to leave things synchronized with the actual code.

    45)Mention what is the command to create a migration?

    Ans) To create migration command includes
    C:\ruby\application>ruby script/generate migration table_name

    46)Explain when self.up and self.down method is used?

    Ans)When migrating to a new version, self.up method is used while self.down method is used to roll back my changes if needed.

    47)Mention what is the difference between Active support’s “HashWithIndifferent” and Ruby’s “Hash” ?

    Ans) The Hash class in Ruby’s core library returns value by using a standard “= =” comparison on the keys. It means that the value stored for a symbol key cannot be retrieved using the equivalent string. While the HashWithIndifferentAccess treats Symbol keys and String keys as equivalent.

    48)Explain what is sweeper in Rails?

    Ans) Sweepers are responsible for expiring or terminating caches when model object changes.

    49)Mention the log that has to be seen to report errors in Ruby Rails?

    Ans)Rails will report errors from Apache in the log/Apache.log and errors from the Ruby code in log/development.log.

    50)Mention what is the purpose of RJs in Rails?

    Ans) RJs is a template that produces JavaScript which is run in an eval block by the browser in response to an AJAX request. It is sometimes used to define the JavaScript, Prototype and helpers provided by Rails.