Ruby Interview Questions And Answers

[TOP 100] Ruby Interview Questions And Answers

Commonly Asked Ruby Interview Questions And Answers

The latest Ruby Interview Questions And Answers are as follows-

1) What is Ruby programming language?

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?

Ruby is designed and developed by Yukihiro “martz” Matsumoto in mid 1990 in Japan.

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

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) List some features of Ruby?

Ruby has many features. Some of them are listed below.

  • Object-oriented
  • Flexible
  • Dynamic typing and Duck typing
  • Garbage collector
  • Keyword arguments

5) Explain some differences between Ruby and Python.

Similarities:

  • High-level language
  • Support multiple platforms
  • Use interactive prompt called irb
  • Server-side scripting language

Differences:

  • Ruby is fully object-oriented while Python is not.
  • Ruby supports EclipseIDE while Python supports multiple IDEs.
  • Ruby use Mixins while Python doesn’t.
  • Ruby supports blocks, procs and lambdas while Python doesn’t.

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

ruby -v

7) What are class libraries in Ruby?

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

8) Name some operators used in Ruby.

Operators are a symbol which is used to perform different operations.

Unary operator

Arithmetic operator

Bitwise operator

Logical operator

Ternary operator

9) What is RubyGems in Ruby programming language?

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.

10) What are Ruby variables.

Ruby variables hold data which can be used later in a program. Each variable act as a memory and shas a different name.

There are four types of variables in Ruby:

Local variable

Class variable

Instance variable

Global variable

11) What is the difference between nil and false in Ruby?

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.

12) Explain Ruby data types.

Ruby data types represent type of data such as text, string, numbers, etc.

There are different data types in Ruby:

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

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

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

In the case of autoloading, it is suggested to use ‘require’.

14) Explain Ruby if-else statement.

The Ruby if-else statement is used to test conditions. There are various types of statements in Ruby.

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

15) Explain case statement in Ruby.

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.

16) Explain for loop in Ruby.

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.

17) Explain while loop in Ruby.

Ruby while loop is used to iterate a program several times. If the number of iterations is not fixed for a program, while loop is used.

18) Explain do while loop in Ruby.

Ruby do while loop iterates a part of program several times. In this, loop will execute at least once because do while condition is written at the end.

19) Explain until loop in Ruby.

Ruby until loop runs until the given condition evaluates to true. It exits the loop when condition becomes true. It is opposite of the while loop.

20) Explain break statement in Ruby.

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.

21) Explain next statement in Ruby.

Ruby next statement is used to skip loop’s next iteration. Once the next statement is executed, no further iteration will be performed.

22) Explain redo statement in Ruby.

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

23) Explain retry statement in Ruby.

Ruby retry statement is used to repeat the whole loop iteration from the start.

24) How will you comment in Ruby.

Ruby comments are non-executable lines in a program. They do not take part in the execution of a program.

Single line comment syntax:

#This is single line comment.

Multi line comment syntax:

=begin

This

is

multi line

comment

=end

25) Explain Ruby object.

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

26) How to create Ruby object?

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

Syntax:

objectName=className.new

27) Explain Ruby class.

Each Ruby class is an instance of Ruby class. Classes in Ruby are first class objects. It always starts with a keyword class followed by the class name.

Syntax:

class ClassName

codes…

end

28) Define Ruby methods.

Ruby method prevent us from writing the same code in a program again and again. Ruby methods are similar to functions in other languages.

29) How to use Ruby methods.

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.

Syntax:

def methodName

code…

end

30) What are Ruby blocks.

Ruby code blocks are called closures in other programming languages. It consist of a group of codes which is always enclosed with braces or written between do…end.

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

A block is written in two ways:

Multi-line between do and end

Inline between braces {}

Both are same and have the same functionality.

syntax:

block_name{

statement1

statement2

……….

}

32) What is yield statement in Ruby.

The yield statement is used to call a block within a method with a value.

33) Explain ampersand parameter (&block) in Ruby.

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.

34) Explain Ruby module.

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

Module name should start with a capital letter.

35) Explain module mixins in Ruby.

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.

36) Explain Ruby strings.

Ruby string object holds and manipulates an arbitary sequence of bytes, typically representing characters. They are created using String::new or as literals.

37) How to access Ruby strings elements in an application.

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

38) How to write multiline string in Ruby.

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.

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

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.

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

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.

41) What are freezing string in Ruby.

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.

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

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

43) What are class libraries in Ruby?

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

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

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

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

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

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

Ruby array elements can be added in different ways.

push or <<

unshift

insert

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

Ruby array elements can be removed in different ways.

pop

shift

delete

uniq

48) Explain Ruby hashes.

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.

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

50) Explain Ruby ranges. What are the ways to define ranges?

Ruby range represents a set of values with a beginning and an end. They can be constructed using s..e and s…e literals or with ::new.

The ranges which has .. in them, run from beginning to end inclusively. The ranges which has … in them, run exclusively the end value.

Ruby has a variety of ways to define ranges.

Ranges as sequences

Ranges as conditions

Ranges as intervals

51) What are Ruby iterators?

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.

52) How many iterators are there in Ruby?

Following iterators are there in Ruby:

each iterator

times iterator

upto and downto iterator

step iterator

each_line iterator

53) Name different methods for IO console in Ruby?

The IO console provides different methods to interact with console. The class IO provides following basic methods:

IO::console

IO#raw#raw!

IO#cooked

IO#cooked!

IO#getch

54) How to open a file in Ruby?

A Ruby file can be created using different methods for reading, writing or both.

There are two methods to open a file in Ruby.

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

File.open 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 File.open method can be associated with a block while File.new method can’t.

Syntax:

f = File.new(“fileName.rb”)

Or,

File.open(“fileName.rb”, “mode”) do |f|

55) How to read a file in Ruby?

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…]

56) Explain class libraries in Ruby.

Ruby class libraries contain a variety of domains like thread programming, data types, and various domains. It has additional libraries evolving day by day. The following are the domains which has relevant class libraries.

Text processing: File, String, Regexp for quick and clean text processing.

CGI Programming: 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.

GUI programming: Ruby/Tk and Ruby/Gtk are the classes for GUI programming

XML programming: UTF-8 text processing regular expression engine make XML programming very handy in ruby.

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

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

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”)

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

To check whether a directory exists or not exists? Method is used.

Syntax:

puts Dir.exists? “dirName”

60) Explain Ruby exceptions.

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.

61) What are some built-in Ruby class exceptions.

Built-in subclasses of exception are as follows:

NoMemoryError

ScriptError

SecurityError

SignalException

62) How an exception is handled in Ruby?

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.

63) Explain the use of retry statement in Ruby?

Usaually in a rescue clause, the exception is captured and code resumes after begin block. Using retry statement, the rescue block code can be resumed from begin after capturing an exception.

Syntax:

begin

code….

rescue

# capture exceptions

retry # program will run from the begin block

end

64) Explain raise statement in Ruby?

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

65) Explain the use of ensure statement in Ruby?

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.

Syntax:

begin

code..

#..raise exception

rescue

#.. exception is rescued

ensure

#.. This code will always execute.

end

Q66) What is a Gemfile?

A Gemfile is where we specify dependencies for a Ruby application. It is located in the project’s root directory.

Q67) What is Gemfile.lock?

It contains records of exact versions of gems installed. This is so the same versions can be installed if another machine clones the project.

In contrast, specifying a gem in a Gemfile without pegging to a specific version will just install the latest version of a gem.

Q68) How does Rails manage database state?

The developer manually generates and adds instructions to migration files.

These instruct ActiveRecord how to modify the existing database state. For this reason, deleting or modifying previous migrations can put the database into a bad state and is not recommended.

Manually creating migration files is in contrast to other frameworks like Django, where the end state of the database is specified and then migrations are auto-generated to make the required changes.

Q69. When would you use a before_save vs. after_save callback?

Updating an object after it’s been saved requires an additional database transaction to persist the update. So, if you are updating an object’s attribute, a before_save callback is more efficient.

But sometimes information does exist on the object until it’s persisted (i.e.: id). So, if an id is required to create an associated record, that would have to be performed in an after_save callback.

Q70. What are initializers in Rails?

Initializers hold configuration logic and only run when an app is booted. This means the Rails server needs to be restarted if initializers are changed. They exist in the /config/initializers directory.

Q71. What is the difference between delete and destroy in Ruby?

delete: Deletes a record.

destroy: Deletes a record and executes callbacks.

The most common callback on destroy in Rails apps is specified on associations in model files. For example, the below destroys related comments when an article is destroyed

Q72. What is the meaning of “Fat models, skinny controllers”?

Business logic should exist in models, not controllers. This makes logic easier to unit test and is more re-usable.

Controllers are merely the hands that pass information between views and models.

This is generally given as advice to new Rails developers. It’s not actually recommended, particularly in large apps.

Q73. What is the meaning of “skinny controllers, skinny models”?

As a codebase grows, fat models get out of hand, start doing too many things and become unmanageable. Models should handle persistence without being bloated with logic.

Models can be made skinnier by keeping the single responsibility principle in mind and moving logic out of models, and into other design patterns like service objects.

Q74. What is a PORO?

PORO stands for “Plain Old Ruby Object”.

Although almost everything in Ruby is an object, ActiveRecord tends to use a lot of complex objects. So, the term PORO is typically to stress a small, simple object used to support business logic.

Q75. Is Ruby strongly or weakly typed?

Ruby is strongly typed. An error will be thrown if you try to calculate “hello” + 3.

In contract, JavaScript is weakly typed and would simply evaluate the same calculation to “hello3”.

Q76. What frameworks have you used for backgrounding jobs?

Delayed::Job: Easy to set up and use. Queues are stored in a database table. If the same database is used for Delayed::Job and production, then a large number of jobs could turn the database into a bottleneck.

Sidekiq: Uses Redis to queue jobs. Redis is an in-memory data store so it’s very fast. Sidekiq adds complexity to infrastructure because Redis needs to be added.

Sucker Punch: Runs as a Ruby process and keeps all jobs in memory. Jobs are lost if the process crashes. Not recommended for critical tasks.

Q77. What logic goes into a helper?

Helper logic should support views only.

A good candidate for a helper is date formatting logic required in several different views.

Q78. What is ActiveRecord?

Active Record is an ORM (object-relational mapping) that maps models to database tables. It simplifies setting up an app because we no longer have to write SQL directly to load, save, or delete objects.

It also provides some protection against SQL injection.

Q79. When do we use “self” in Ruby?

Use self when defining and calling class methods.

In a class, self refers to the current class so it’s required when a class method calls another class method.

self.class.method is required when an instance calls a class method.

Q80. What is Rack?

Rack is an API sitting between the web server and Rails. It allows plugging in and swapping frameworks like Rails with Sinatra, or web servers like Unicorn with Puma.

Q81. What is a block in Ruby?

A block is the code between two braces, {…}, or between do and end. You’re passing a block every time you call .each.

Blocks have their own scope and variables only defined inside a block are not accessible outside. But variables defined outside a block can be modified inside a block.

{|x| puts x} # a block

Q82. What is content_for for?

It allows defining and rendering content in views. This is useful for defining content in one place and rendering it in many.

Q83. What is the difference between Hash and JSON?

Hash is a Ruby class, a collection of key/value pairs that allows accessing values by keys.

JSON is a string in a specific format for sending data.

Q84. What is the splat operator?

Splat is used when you don’t want to specify the number of arguments passed to a method in advance. Ruby has two splat operators, the single splat and double splat.

Q85. What is the difference between load and require in Ruby?

load runs another file, even if it’s already in memory.

require will only run another file once, no matter how many times you require it.

Q86. What is the difference between find, find_by, and where in ActiveRecord?

find: Takes a single argument and looks up the record where the primary key matches that argument.

find_by: Takes key/values and returns the first matching record.

where: Takes key/values and returns a collection of matching records. Or an empty collection if there are no matches.

Q87. What is the difference between select, map, and collect?

All three methods take a block as an argument.

select: Is used to grab a subset of a collection. Calling .select! with a bang mutates the original collection.

i = [1,2,3,4,5]

i.select {|x| x % 2 == 0}

# => [2, 4]

map: Performs an action on each element of a collection and outputs an updated collection. Calling .map! with a bang mutates the original collection.

i = [1,2,3,4,5]

i.map {|x| x+1}

# => [2,3,4,5,6]

collect: Is an alias of .map and does the same thing.

Q88. Define a route for a create action without using “resources”

With resources: resources :photos.

Without resources: post ‘/photos’, to: ‘photos#create’, as: :create_photo.

Q89. What are the three levels of access control?

public: Any object can call this method.

protected: Only the class that defined the method and its subclasses can call the method.

private: Only the object itself can call this method

Q90. How do you use singletons in Ruby?

A singleton is a design pattern that only allows a class to have one instance. This is typically frowned upon in Ruby, but Ruby does come with a module for it.

require ‘singleton’

class Thing

include Singleton

end

puts Thing.instance

# => #<Thing:0x00007fdd492cf488>

 

Related Posts:

For more Interview Questions And Answers click here

 

1 thought on “[TOP 100] Ruby Interview Questions And Answers

  1. Pingback: Puppet Interview Questions And Answers - CloudNClear

Comments are closed.