Ruby Interview Questions and Answers
Practice Ruby interview questions and answers organized by difficulty, with revealable explanations and related topics.
Entry questions
9 questions- Question 1Entry
Is everything in Ruby an object?
- Ruby
Reveal answerHide answer
Methods are not objects. Blocks are not objects. Keywords are not objects. However, there exist Method objects and Proc objects, and some keywords refer to objects.
- Question 2Entry
Why Ruby is known as a language of flexibility?
- Ruby
Reveal answerHide answer
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.
- Question 3Entry
What is an object?
- Ruby
Reveal answerHide answer
An instance of a class. To some, it's also the root class in ruby (Object). Classes themselves descend from the Object root class.
- Question 4Entry
What is a class?
- Ruby
Reveal answerHide answer
Classes hold data, have methods that interact with that data, and are used to instantiate objects. class WhatAreClasses def initialize @data = "I'm instance data of this object. Hello." end def method
puts @data.gsub("instance", "altered") end end object = WhatAreClasses.new object.method #=> I'm altered data of this object. Hello. - Question 5Entry
What are rubygems?
- Ruby
Reveal answerHide answer
rubygems is package manager software for ruby libraries (i.e. gems). The package manager has basic CRUD operations, dependency trees, and supports asynchronous communication between multiple gem servers.
- Question 6Entry
Is there an equivalent of “continue” in Ruby?
- Ruby
Reveal answerHide answer
Yes, it's called next . for i in 0..5 if i < 2 next end puts "Value of local variable is #{i}" end
- Question 7Entry
What can you say about an identifier that begins with a capital letter?
- Ruby
Reveal answerHide answer
It is a constant.
- Question 8Entry
Which core object includes the "Kernel" module?
- Ruby
Reveal answerHide answer
Object
- Question 9Entry
What is the highest level in the object model?
- Ruby
Reveal answerHide answer
BasicObject
Junior questions
30 questions- Question 1Junior
What does it mean to coerce an object? Why would you do it?
- Ruby
Reveal answerHide answer
To coerce an object means to force it into an expected type. One might do this in order to try and force an unknown object type into the expected type or format required by the operation. This is a common practice involved in duck typing.
- Question 1Junior
What is duck typing and how does it pertain to Ruby?
- Ruby
Reveal answerHide answer
That an object may be acted upon even if it isn't the expected type as long as it looks and behaves like the expected object. This is a characteristic of Ruby because the lack of type checking of parameters makes this an effective programming technique.
- Question 2Junior
Are instance methods public or private?
- Ruby
Reveal answerHide answer
They are public by default. You can change their visibility using Module#private , Module#protected , or back again using Module#public .
- Question 2Junior
What is the difference between nil and false in Ruby?
- Ruby
Reveal answerHide answer
nil: nil cannot be a value nil is returned where there is no predicate nil is not a boolean data type nil is an object of nilclass false: false can be a value in case of a predicate, true or false is returned by a method false is a boolean data type false is an object of falseclass
- Question 3Junior
Explain some differences between Ruby and Python
- Ruby
Reveal answerHide answer
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.
- Question 3Junior
Which of the expressions listed below will result in "false"?
- Ruby
Reveal answerHide answer
Problem
true ? "true" : "false" false ? "true" : "false" nil ? "true" : "false" 1 ? "true" : "false" 0 ? "true" : "false" "false" ? "true" : "false" "" ? "true" : "false"
[] ? "true" : "false" ### SolutionIn Ruby, the only values that evaluate to false are false and nil . Everything else – even zero (0) and an empty
array ([]) – evaluates to true.This comes as a real surprise to programmers who have previously been working in other languages like JavaScript.
- Question 4Junior
Explain each of the following operators and how and when they should be used
- Ruby
Reveal answerHide answer
Problem
== === eql? equal? ### Solution == – Checks if the value of two operands are equal (often overridden to provide a class-specific definition of equality). === – Specifically used to test equality within the when clause of a case statement (also often overridden to provide meaningful class-specific semantics in case statements). eql? – Checks if thevalue and type of two operands are the same (as opposed to the == operator which compares values but ignores types). For example, 1 == 1.0 evaluates to true , whereas 1.eql?(1.0) evaluates to false . equal? – Compares the identity of two objects; i.e., returns true iff both operands have the same object id (i.e., if they both refer to the same object). Note that this will return false when comparing two identical copies of the same object.
- Question 5Junior
Can you call a private method outside a Ruby class using its object?
- Ruby
Reveal answerHide answer
Yes, with the help of the send method. Given the class Test :
class Test private def method p "I am a private method" end end We can execute the private method using send :
>> Test.new.send(:method) "I am a private method" - Question 5Junior
What will be the values of ...
- Ruby
Reveal answerHide answer
Problem
Consider the following code: class A
def self.a(b) if b > 0 b * b end end endWhat will be the values of:
var1 = A.a(0) var2 = A.a(2) ### Solutionvar1 will be equal to nil var2 will be equal to 4 A conditional statement in Ruby is an expression that returns nil if the conditional is false . Ruby methods return the last expression in the method body.
- Question 6Junior
What is the difference between nil and false in Ruby?
- Ruby
Reveal answerHide answer
nil: nil cannot be a value nil is returned where there is no predicate nil is not a boolean data type nil is an object of nilclass false: false can be a value in case of a predicate, true or false is returned by a method false is a boolean data type false is an object of falseclass
- Question 8Junior
There are three ways to invoke a method in ruby. Can you give me at least two?
- Ruby
Reveal answerHide answer
We are looking for the dot operator (or period operator), the Object#send method, or method(:foo).call
object = Object.new puts object.object_id #=> 282660 puts object.send(:object_id) #=> 282660 puts object.method(:object_id).call # (Kudos to Ezra) #=> 282660 - Question 10Junior
Why might you use #each instead of for/in ?
- Ruby
Reveal answerHide answer
It's the "Ruby way" - an example of how Ruby defines methods that mimic natural language concepts. Iterator methods such as #each read more naturally. #each is a block so it defines a new variable scope. for/in depends on the existence of #each which implies that #each is a more fundamental aspect of the language.
- Question 10Junior
Are class variables inherited?
- Ruby
Reveal answerHide answer
No. The behavior is different than inheritance. Any alteration of a class variable by a subclass affects that class variable in the superclass and all other subclasses of the superclass.
- Question 11Junior
What is a predicate in the context of Ruby method naming conventions?
- Ruby
Reveal answerHide answer
A method that answers a question posed by the method invocation or method name. Predicates typically return a boolean.
$ irb > 5.odd? => true > 5.even? => false > 5.between?(1, 10) => true > 5.between?(11, 20) => false - Question 11Junior
What is the difference between an Instance Variable and a Class Variable?
- Ruby
Reveal answerHide answer
A class variable is evaluated in reference to the class object created by the enclosing class definition while an instance variable is evaluated in reference to self . Instance variables cannot be referenced outside of instance methods.
- Question 12Junior
What is the difference between private and protected methods?
- Ruby
Reveal answerHide answer
A private method can only be called by any instance methods of the defining class or any subclasses and must be invoked in a functional style and not explicitly on self such as with self.my_method . A protected method may be explicitly invoked by any instance of the defining class, and is not restricted to implicit invocation on self .
- Question 12Junior
Are instance methods public or private?
- Ruby
Reveal answerHide answer
They are public by default. You can change their visibility using Module#private , Module#protected , or back again using Module#public .
- Question 13Junior
What is the difference between a class variable and a class instance variable?
- Ruby
Reveal answerHide answer
Class instance variables are instance variables of a class. Class instance variables cannot be used within instance methods.
- Question 13Junior
What is the difference between #== and #=== ?
- Ruby
Reveal answerHide answer
#== performs the generic comparison while #=== performs case equality comparison and is useful for providing meaningful semantics in case statements.
- Question 14Junior
How might you specify a default value for a hash?
- Ruby
Reveal answerHide answer
Pass the default values as arguments to ::new on initialization or change the default directly with the method Hash#default . You may also provide a default at the time of query with Hash#fetch .
- Question 14Junior
What are two uses of the splat operator?
- Ruby
Reveal answerHide answer
Explode or expand the elements of an array. Collect arguments of a parameter list into an array.
- Question 15Junior
Is Ruby a strongly typed or a weakly typed language?
- Ruby
Reveal answerHide answer
Strongly typed since an object's type is checked before an operation is performed on it.
- Question 15Junior
Why might you use Hash#fetch over Hash#[] when querying values in a hash?
- Ruby
Reveal answerHide answer
Hash#fetch provides options for handling the case where a key does not exist in the hash.
- Question 16Junior
What is a module? Can you tell me the difference between classes and modules?
- Ruby
Reveal answerHide answer
Modules serve as a mechanism for namespaces. module ANamespace class AClass def initialize puts "Another object, coming right up!" end end end ANamespace::AClass.new
#=> Another object, coming right up!Also, modules provide as a mechanism for multiple inheritance via mix-ins and cannot be instantiated like classes can. module AMixIn def who_am_i? puts "An existentialist, that's who." end end# String is already the parent class
class DeepString < String # extend adds instance methods from AMixIn as class methods extend AMixIn end DeepString.who_am_i? #=> An existentialist, that's who. AMixIn.new #=> NoMethodError: undefined method ‘new’ for AMixIn:Module - Question 16Junior
Why are symbols typically used as hash keys instead of strings?
- Ruby
Reveal answerHide answer
Strings are mutable while symbols are immutable. Though Ruby internally makes an immutable copy of a string when used as a hash key, comparing two symbols is faster than comparing two String objects. This is also a convention.
- Question 17Junior
What does it mean to coerce an object? Why would you do it?
- Ruby
Reveal answerHide answer
To coerce an object means to force it into an expected type. One might do this in order to try and force an unknown object type into the expected type or format required by the operation. This is a common practice involved in duck typing.
- Question 18Junior
Is Ruby a statically typed or a dynamically typed language?
- Ruby
Reveal answerHide answer
Dynamically typed since type checking is done at runtime.
- Question 19Junior
How do you remove nil values in array using ruby?
- Ruby
Reveal answerHide answer
Array#compact removes nil values.
>> [nil,123,nil,"test"].compact => [123, "test"] - Question 19Junior
What is a DSL and how does it pertain to Ruby?
- Ruby
Reveal answerHide answer
A Domain Specific Language is an API that allows a developer to solve a problem or represent data more naturally than they might otherwise. The flexible nature of Ruby's syntax and the ability to alias and alter existing methods and classes makes it conducive to creating rich DSL's.
- Question 20Junior
Explain redo statement in Ruby
- Ruby
Reveal answerHide answer
Ruby redo statement is used to repeat the current iteration of the loop. The redo statement is executed without evaluating loop's condition.
Mid questions
30 questions- Question 1Mid
What is the difference between Proc invocation and lambda invocation?
- Ruby
Reveal answerHide answer
A block must be associated with lambda invocation. Lambdas must be invoked with the exact number of arguments such as is required by method invocation, whereas procs are more flexible in receiving arguments.
- Question 1Mid
What are two uses of ranges?
- Ruby
Reveal answerHide answer
comparison iteration
- Question 2Mid
What is the difference between Array#map and Array#each ?
- Ruby
Reveal answerHide answer
Array#each method iterates over the elements of the array and executes the provided block each time. However, it returns the original array unaffected. Array#map will return a new array of elements containing the values returned by the block it is provided. It also does not affect the original array
- Question 4Mid
What is the difference between calling "super" and calling "super()"
- Ruby
Reveal answerHide answer
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. As always, being explicit in your code is a good thing.
- Question 4Mid
What is the difference between Kernel#require and Kernel#load ?
- Ruby
Reveal answerHide answer
Kernel#require can load binary extensions. Kernel#require does not require a filename extension. Kernel#require prevents multiple loads of the same file path. Kernel#load loads the specified file at the current $SAFE level while Kernel#require loads the specified file with a $SAFE level of 0.
- Question 5Mid
How is the invocation of a private method different than the invocation of a public method from within its defining class?
- Ruby
Reveal answerHide answer
It must be referenced in a functional manner without an explicit receiver object and not on the class object itself or on the current object self .
- Question 6Mid
What is a Proc?
- Ruby
Reveal answerHide answer
Essentially, Procs are anonymous methods (or nameless functions) containing code. They can be placed inside a variable and passed around like any other object or scalar value. They are created by Proc.new, lambda, and blocks (invoked by the yield keyword). Note: Procs and lambdas do have subtle, but important, differences in ruby v1.8.6. However, I wouldn't expect a candidate talk about these nitty-gritty details during an interview. (Kudos to Noah Thorp)
# wants a proc, a lambda, AND a block def three_ways(proc, lambda, &block) proc.call lambda.call yield # like block.call puts "#{proc.inspect} #{lambda.inspect} #{block.inspect}" end anonymous = Proc.new { puts "I'm a Proc for sure." } nameless = lambda { puts "But what about me?" } three_ways(anonymous, nameless) do puts "I'm a block, but could it be???" end #=> I'm a Proc for sure. #=> But what about me? #=> I'm a block, but could it be??? #=> #<Proc:0x00089d64> #<Proc:0x00089c74> #<Proc:0x00089b34> - Question 6Mid
What is an iterator?
- Ruby
Reveal answerHide answer
An object that allows traversal of the elements of the container. In Ruby, an iterator is typically considered any method that uses the yield statement.
- Question 7Mid
Why can you safely use a string as a hash key, even though a string is mutable?
- Ruby
Reveal answerHide answer
Because the interpreter makes a private copy of a string used as a hash key.
- Question 7Mid
What does self mean?
- Ruby
Reveal answerHide answer
self always refers to the current object. But this question is more difficult than it seems because Classes are also objects in ruby. class WhatIsSelf def test puts "At the instance level, self is #{self}" end def self.test puts "At the class level, self is #{self}" end end WhatIsSelf.test #=> At the class level, self is WhatIsSelf
WhatIsSelf.new.test #=> At the instance level, self is #WhatIsSelf:0x28190 This short snippet indicates two things: at the class level, self is the class, in this case WhatIsSelf. at the instance level, self is the instance in context, in this case the instance of WhatIsSelf at memory location 0x28190.
- Question 7Mid
What are some disadvantages of a case statement versus repeated elsif statements?
- Ruby
Reveal answerHide answer
The statement is typically resistant to modification without a complete refactoring of the entire control structure. The case statement can be confusing if multiple comma-separated expressions are associated with a single when clause.
- Question 8Mid
What does a bang ! at the end of a method signify?
- Ruby
Reveal answerHide answer
That it should be with caution. Methods with this naming convention typically perform a *mutation on the receiver object.
- Question 8Mid
Explain this ruby idiom: a ||= b
- Ruby
Reveal answerHide answer
Is it a common idiom that strong ruby developers will use all the time.
# a = b when a == false # otherwise a remains unchanged a || a = b # (Kudos to Markus Prinz) a = 1 b = 2 a ||= b #=> a = 1 a = nil b = 2 a ||= b #=> a = 2 a = false b = 2 a ||= b #=> a = 2 - Question 8Mid
What is the difference between #== and #eql? ?
- Ruby
Reveal answerHide answer
#eql? is sometimes an alternate equality. Hash uses #eql? to test for hash key equality. Numeric types perform type conversion across #== but not across #eql? , thus #eql? performs a stricter comparison than #== in that case.
- Question 9Mid
Describe a closure in Ruby
- Ruby
Reveal answerHide answer
A closure is an object that is both an invocable function together with a variable binding. The object retains access to the local variables that were in scope at the time of the object definition. A closure in Ruby retain variables by reference; the closure also extends the lifetimes of its variables. A closure's reference to its variables is dynamically bound that means the values of the variables are resolved when the Proc object is executed. It also possible to alter a closure. The binding of a closure can be altered using #binding .
- Question 9Mid
Can you tell me the three levels of method access control for classes and modules? What do they imply about the method?
- Ruby
Reveal answerHide answer
All methods, no matter the access control, can be accessed within the class. But what about outside callers? Public methods enforce no access control -- they can be called in any scope. Protected methods are only accessible to other objects of the same class. Private methods are only accessible within the context of the current object. class AccessLevel def something_interesting
another = AccessLevel.new another.public_method another.protected_method another.private_method end def public_methodputs "Public method. Nice to meet you." end protected def protected_method puts "Protected method. Sweet!" end private def private_method puts "Incoming exception!" end end AccessLevel.new.something_interesting #=> Public method. Nice to meet you.
#=> Protected method. Sweet! #=> NoMethodError: private method ‘private_method’ called for #=> #<AccessLevel:0x898c8> - Question 9Mid
Why can you safely use a string as a hash key, even though a string is mutable?
- Ruby
Reveal answerHide answer
Because the interpreter makes a private copy of a string used as a hash key.
- Question 10Mid
Describe a closure in Ruby
- Ruby
Reveal answerHide answer
A closure is an object that is both an invocable function together with a variable binding. The object retains access to the local variables that were in scope at the time of the object definition. A closure in Ruby retain variables by reference; the closure also extends the lifetimes of its variables. A closure's reference to its variables is dynamically bound that means the values of the variables are resolved when the Proc object is executed. It also possible to alter a closure. The binding of a closure can be altered using #binding .
- Question 10Mid
Can you tell me the three levels of method access control for classes and modules? What do they imply about the method?
- Ruby
Reveal answerHide answer
All methods, no matter the access control, can be accessed within the class. But what about outside callers? Public methods enforce no access control -- they can be called in any scope. Protected methods are only accessible to other objects of the same class. Private methods are only accessible within the context of the current object. class AccessLevel def something_interesting
another = AccessLevel.new another.public_method another.protected_method another.private_method end def public_methodputs "Public method. Nice to meet you." end protected def protected_method puts "Protected method. Sweet!" end private def private_method puts "Incoming exception!" end end AccessLevel.new.something_interesting #=> Public method. Nice to meet you.
#=> Protected method. Sweet! #=> NoMethodError: private method ‘private_method’ called for #=> #<AccessLevel:0x898c8> - Question 11Mid
Why might you want to avoid using string literals within loops?
- Ruby
Reveal answerHide answer
A new object is created for every string literal even when the values are identical. Consider using variables or symbols instead.
- Question 11Mid
What does self mean?
- Ruby
Reveal answerHide answer
self always refers to the current object. But this question is more difficult than it seems because Classes are also objects in ruby. class WhatIsSelf def test puts "At the instance level, self is #{self}" end def self.test puts "At the class level, self is #{self}" end end WhatIsSelf.test #=> At the class level, self is WhatIsSelf WhatIsSelf.new.test #=> At the instance level, self is #WhatIsSelf:0x28190
This short snippet indicates two things: at the class level, self is the class, in this case WhatIsSelf. at the instance level, self is the instance in context, in this case the instance of WhatIsSelf at memory location 0x28190.
- Question 12Mid
What is the main difference between procs and lambdas?
- Ruby
Reveal answerHide answer
Calling a lambda is more akin to invoking a method where a return statement in a lambda will return from the lambda itself, instead of returning from the lexically enclosing method, as procs do. Adding to this notion, lambdas must be invoked with the exact number of arguments such as is required by method invocation, whereas procs are more flexible in receiving arguments.
- Question 13Mid
What is the difference between Module#remove_method and Module#undef_method ?
- Ruby
Reveal answerHide answer
Module#undef_method prevents any invocation of the method through an instance of the class, while Module#remove_method will remove the method definition from the class, but not prevent inherited methods of the same name from being invoked.
- Question 14Mid
Why might you want to alias a method?
- Ruby
Reveal answerHide answer
To create a synonym for an existing method that is more readable or appropriate in the context of some problems or to add functionality to an existing method.
- Question 15Mid
What does a bang ! at the end of a method signify?
- Ruby
Reveal answerHide answer
That it should be with caution. Methods with this naming convention typically perform a *mutation on the receiver object.
- Question 16Mid
How does block invocation differ from method invocation?
- Ruby
Reveal answerHide answer
Ruby will throw an exception if more than the expected number of arguments are passed to a method. A block will simply ignore the extra values.
- Question 17Mid
When might you use the do / end syntax versus using the curly bracket syntax for a block?
- Ruby
Reveal answerHide answer
The do / end syntax for a block is commonly used for multi-line statements. An alternate convention is to use curly bracket syntax for blocks that return a value while using do / end syntax for blocks that change the state of the system somehow and do not return a value.
- Question 18Mid
What is the difference between throw/catch and raise/rescue ?
- Ruby
Reveal answerHide answer
throw and catch accept matching symbols as arguments and should be considered a control-flow structure where raise and rescue is used to raise and handle exceptions. throw and catch are not commonly used while exception handling with raise and rescue is used often.
- Question 19Mid
What is the difference between #== and #equal? ?
- Ruby
Reveal answerHide answer
#== performs the generic comparison and is implemented differently across classes while #equal? is defined on BasicObject and compares object identity. Therefore, #equal? should not be overridden in subclasses.
- Question 20Mid
Explain redo vs. retry usage
- Ruby
Reveal answerHide answer
redo and retry are both used to re-execute parts of a loop. But they differ in how much they re-execute: redo only repeats the current iteration, while retry repeats the whole loop from the start.
Senior questions
14 questions- Question 3Senior
Write a single line of Ruby code that prints the Fibonacci sequence of any length as an array.
- Ruby
Reveal answerHide answer
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 resultto the end of fib . Note: inject is an alias of reduce
- Question 10Senior
Is a block an object?
- Ruby
Reveal answerHide answer
No. A block is a syntactic structure of the interpreter. A block can be converted to a Proc object.
- Question 11Senior
What happens if a block is passed two arguments but only accepts one argument?
- Ruby
Reveal answerHide answer
Nothing. Only the first argument will be passed to the block.
- Question 12Senior
Why doesn't Ruby support method overloading?
- Ruby
Reveal answerHide answer
Overloading is a term that simply doesn't even make sense in Ruby. It is basically a synonym for "static argument-based dispatch", but Ruby doesn't have static dispatch at all. So, the reason why Ruby doesn't support static dispatch based on the arguments, is because it doesn't support static dispatch, period. It doesn't support static dispatch of any kind, whether argument-based or otherwise.
- Question 12Senior
Is a block an object?
- Ruby
Reveal answerHide answer
No. A block is a syntactic structure of the interpreter. A block can be converted to a Proc object.
- Question 13Senior
Is a method an object?
- Ruby
Reveal answerHide answer
No, however, a Method object is of course, an object.
- Question 13Senior
When might you encounter a LocalJumpError ?
- Ruby
Reveal answerHide answer
You might typically encounter this exception when attempting to yield when no block is given. You might also encounter this exception when attempting to return from a method that has already returned such as if you attempt to return from a Proc object whose lexically enclosing method has already returned.
- Question 14Senior
When might you encounter a LocalJumpError ?
- Ruby
Reveal answerHide answer
You might typically encounter this exception when attempting to yield when no block is given. You might also encounter this exception when attempting to return from a method that has already returned such as if you attempt to return from a Proc object whose lexically enclosing method has already returned.
- Question 14Senior
What is the primary difference in these two code snippets?
- Ruby
Reveal answerHide answer
Problem
// Java public boolean isEmpty(String s) { return s.length() == 0; } # ruby def empty?(s) return s.size == 0 end ### SolutionThe 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.
- Question 15Senior
What happens to a constant which is not assigned?
- Ruby
Reveal answerHide answer
It does not exist.
- Question 15Senior
Write a single line of Ruby code that prints the Fibonacci sequence of any length as an array.
- Ruby
Reveal answerHide answer
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 resultto the end of fib . Note: inject is an alias of reduce
- Question 16Senior
What is an eigenclass?
- Ruby
Reveal answerHide answer
An anonymous class associated with an object. An object's singleton methods are instance methods of its associated eigenclass.
- Question 17Senior
What is the difference between Object#dup and #clone ?
- Ruby
Reveal answerHide answer
#clone copies the frozen state of an object and any singleton methods of an object while Object#dup does neither.
- Question 18Senior
What is the difference between BasicObject#instance_eval and BasicObject#instance_exec ?
- Ruby
Reveal answerHide answer
BasicObject#instance_exec can only accept a block, not a string, and it can accept arguments and pass them to the block, allowing the block to be evaluated in the context of the receiver object with parameters whose values come from the block.
Expert questions
1 questions- Question 4Expert
What is the differnece between extend and include in ruby?
- Ruby
Reveal answerHide answer
include mixes in specified module methods as instance methods in the target class extend mixes in specified module methods as class methods in the target class Given the following class definitions: module ReusableModule def module_method puts "Module Method: Hi there! I'm a module method" end end class ClassThatIncludes include ReusableModule end class ClassThatExtends extend ReusableModule end Here’s how ClassThatIncludes behaves:
A class method does not exist
ClassThatIncludes.module_method NoMethodError: undefined method `module_method' for ClassThatIncludes:Class
# A valid instance method exists >> ClassThatIncludes.new.module_method Module Method: Hi there! I'm a module method => nil Here’s how ClassThatExtends behaves: # A valid class method exists >> ClassThatExtends.module_method Module Method: Hi there! I'm a module method => nil # An instance method does not exist ClassThatExtends.new.module_method NoMethodError: undefined method `module_method' for #<ClassThatExtends:0x007ffa1e0317e8>We should mention that object.extend ExampleModule makes ExampleModule methods available as singleton methods in the object.