Ruby Interview Questions
Ruby Interview Questions
1. What is a class method and how you will define it?
Class methods are methods that are called on a class without creating instance of that class.
# Way 1 # Way 2 #Way3
class Foo class Foo class Foo; end
def self.bar class << self def Foo.bar
puts 'class method' def bar puts 'class method'
end puts 'class method' end
end end end end
Calling class method => Foo.bar
2. What is an instance method and how you will instantiate it?
Instance methods are methods that are called on an instance of a class.
# Way 1 # Way 2 # Way 3
class Foo class Foo class Foo; end
def baz attr_accessor :baz foo = Foo.new
puts 'instance method' end def foo.bar
end foo = Foo.new puts 'instance method'
end foo.baz = 'instance method' end
Instantiating instance methods:
a). f = Foo.new
f.bar
b). g = Foo.new
g.send(:bar)
c). Foo.new.bar
3. What is singleton class and singleton method ? (http://www.devalot.com/articles/2008/09/ruby-singleton)
A singleton method is a method that is defined only for a single object.
o = "message" # A string is an object
def o.printme # Define a singleton method for this object
puts self
end
o.printme # Invoke the singleton
A method added to a single object rather than to a class of objects is known as a singleton method.
The implicit class object to which such singleton methods are added is sometimes called a singleton class or singel class instead.
4. What are the closures in ruby?
In Ruby, procs and lambdas are closures . Closure refers to an object that is both an invocable function and a variable binding for that function.
When you create a proc or a lambda, the resulting Proc object holds not just the executable block but also bindings for all the variables used by the block.
5. What is the difference between Proc and Lambda?
http://railsknowledge.blogspot.in/2014/10/what-is-difference-between-proc-and.html
6. What is the difference between Ruby 1.8.7 and 1.9.2?
http://railsknowledge.blogspot.in/2014/10/what-is-difference-between-ruby-187-and.html
7. What is a module and what is the use of it?
Like a class, a module is a named group of methods, constants, and class variables.
Modules are defined much like classes are, but the module keyword is used in place of
the class keyword. Unlike a class, however, a module cannot be instantiated, and it cannot be subclassed. Modules stand alone; there is no “module hierarchy” of inheritance. Modules are used as namespaces and as mixins.
Namespaces:
Modules are a good way to group related methods when object-oriented programming
is not necessary.
Mixins:
The second use of modules mixins. If a module defines instance methods instead of the class methods, those instance methods can be mixed in to other classes.
8. What is the difference between collect,select, reject and inject in ruby?
http://railsknowledge.blogspot.in/2014/10/what-is-difference-between.html
9. What is Enumerator in ruby?
An enumerator is an Enumerable object whose purpose is to enumerate some other object. To use enumerators in Ruby 1.8, you must require 'enumerator' . In Ruby 1.9, enumerators are built-in and no require is necessary.
10.Difference between ‘load’ and ‘require’ in Ruby?
The difference between load and require is that load includes the specified Ruby file every time the method is executed and require includes the Ruby file only once.
• In addition to loading source code, require can also load binary extensions to Ruby. Binary extensions are, of course, implementation-dependent, but in C-based implementations, they typically take the form of shared library files with extensions like .so or .dll .
• load expects a complete filename including an extension. require is usually passed a library name, with no extension, rather than a filename. In that case, it searches for a file that has the library name as its base name and an appropriate source or native library extension. If a directory contains both an .rb source file and a binary extension file, require will load the source file instead of the binary file.
• load can load the same file multiple times. require tries to prevent multiple loads of the same file. (require can be fooled, however, if you use two different, but equivalent, paths to the same library file. In Ruby 1.9, require expands relative paths to absolute paths, which makes it somewhat harder to fool.) require keeps track of the files that have been loaded by appending them to the global array
$" (also known as $LOADED_FEATURES ). load does not do this.
• load loads the specified file at the current $SAFE level. require loads the specified library with $SAFE set to 0 , even if the code that called require has a higher value for that variable. See §10.5 for more on $SAFE and Ruby’s security system. (Note that if $SAFE is set to a value higher than 0 , require will refuse to load any file with a tainted filename or from a world-writable directory. In theory, therefore, it should be safe for require to load files with a reduced $SAFE level.)
11. What is string interpolation in Ruby?
We can embedded an expression in double coded string using curly brackets preceding with #. This is called string interpolation.
Name =”vijay”
Puts “My name is #{name}”
12. what is the difference between dup and clone methods in Ruby?
The Ruby built-in methods Object#clone and #dup produce copies of their receiver. They differ in the amount of context they copy. The dup method copies just the object's content, whereas clone also preserves things such as singleton classes associated with the object.
s1 = "cat"
def s1.upcase
"CaT"
end
s1_dup = s1.dup
s1_clone = s1.clone
s1 #=> "cat"
s1_dup.upcase #=> "CAT" (singleton method not copied)
s1_clone.upcase #=> "CaT" (uses singleton method)
13. Difference between include and extend in Ruby?
Include is for adding methods to an instance of a class and extend is for adding class methods
module Foo
def foo
puts 'heyyyyoooo!'
end
end
class Bar
include Foo
end
Bar.new.foo # heyyyyoooo!
Bar.foo # NoMethodError: undefined method ‘foo’ for Bar:Class
class Baz
extend Foo
end
Baz.foo # heyyyyoooo!
Baz.new.foo # NoMethodError: undefined method ‘foo’ for #<Baz:0x1e708>
As you can see, include makes the foo method available to an instance of a class and extend makes the foo method available to the class itself.
14. Defining attr_access like methods in Ruby?
class Demo
def self.test_accessor (*args)
args.each do |e|
define_method(e) do
puts instance_variable_get("@#{e}")
end
define_method("#{e}=") do |val|
instance_variable_set("@#{e}",val)
end
end
end
test_accessor :hello,:vijay
end
15. What is the output of x=1/2 in ruby?
0 # zero
Division of one integer by another results in a truncated integer. This is a feature, not a bug. If you need a floating point number, make sure that at least one operand is a floating point.
16. Write a method in Ruby to display given number of Fibonacci series?
def fibonacci(n)
a,b = 0,1
n.times do
printf("%d\n", a)
a,b = b,a+b
end
end
17. Difference between String and Symbol in ruby?
Symbols are Strings, just with an important difference, Symbols are immutable. Mutable objects can be changed after assignment while immutable objects can only be overwritten.
String: Strings are mutable, the Ruby interpreter never knows what that String may hold in terms of data. As such, every String needs to have its own place in memory.
Example:
puts "hello world".object_id # => 3102960
puts "hello world".object_id # => 3098410
Symbol: Every Symbol shares the same object id, and as such the same space on the heap. To further increase performance, Ruby will not mark Symbols for destruction, allowing you to reuse them again and again. Symbols are not only stored in memory, they are also keep track of via an optimized Symbols dictionary.
Example:
puts :"hello world".object_id # => 239518
puts :"hello world".object_id # => 239518
18. What is true, false and nil in ruby?
true evaluates to an object that is a singleton instance of TrueClass. Likewise, false and nil are singleton instances of FalseClass and NilClass.
Note that true, false, and nil refer to objects, not numbers. false and nil are not the same thing as 0, and true is not the same thing as 1. nil behaves like false, and any value other than nil or false behaves like true.
19. Garbage collection in Ruby?
ObjectSpace.garbage_collect, which forces Ruby’s garbage collector to run. Garbage collection functionality is also available through the GC module. GC.start is a synonym for ObjectSpace.garbage_collect. Garbage collection can be temporarily disabled with GC.disable, and it can be enabled again with GC.enable.
20. Program to find given String is palindrome or not?
def palindrome?(str)
str.length <= 1 or (str[0,1] == str[-1,1] and palindrome?(str[1..-2]))
end
puts palindrome?("aja")
Without Recursion call:
def palindrome?(string)
string == string.reverse
end
21. Difference between Array and Hash in Ruby?
Arrays: Arrays are used to store collections of data. Each object in an array has an unique key assigned to it.
We can access any object in the array using this unique key.
The positions in an array starts from " 0 ". The first element is located at " 0 ", the second at 1st position etc.
A Hash is a collection of key-value pairs. It is similar to an Array, except that indexing is done via arbitrary keys of any object type,
not an integer index.
Hashes enumerate their values in the order that the corresponding keys were inserted.
So we use arrays when the order matters
We use hashes when we want the convenience of refering to objects by their labels
22. Program to reverse the given line in Ruby?
words = %w(Son I am able she said)
str = ""
words.reverse_each { |w| str += "#{w} "} # str is now "said she able am I Son "
23. Program to find given number is prime or not?
def prime?(n)
prime = false
factor = 1
if n== 0 or n == 1
prime = false
end
for i in 1..(n-1)
if n%i == 0
factor = i
end
end
if factor > 1
prime = false
else
prime = true
end
return prime
end
24. Program to find given number is palindrome or not ?
def palindrome?(n)
num = n
while n>0
dig = n%10
reverse = reverse*10 + dig
n = n/10
end
if num == reverse
return true
else
return false
end
end
25. Program to find given number is odd or even?
def odd_even?(n)
if n%2 == 0
return true
else
return false
end
end
26. Program to print reverse of the given string?
def str_reverse str
reverse = ‘ ‘
chars = str.each_char.to_a
chars.size.times { reverse << chars.pop}
puts reverse
end
27. How to instantiate a module self.method in a class?
If you want to have both class methods and instance methods mixed into a class when including a module, you may follow the pattern:
YourModule
module ClassMethods
def a_class_method
puts "I'm a class method"
end
end
def an_instance_method
puts "I'm an instance method"
end
def self.included(base)
base.extend ClassMethods
end
end
class Whatever
include YourModule
end
Whatever.a_class_method
# => I'm a class methodmodule
Whatever.new.an_instance_method
# => I'm an instance method
28. Object-oriented programming in Ruby
http://railsknowledge.blogspot.in/2014/10/object-oriented-programming-in-ruby.html