All interview topics
Full-Stack, Web & Mobile

Ruby Interview Questions and Answers

Practice Ruby interview questions and answers organized by difficulty, with revealable explanations and related topics.

84 questionsEntry → Expert

Entry questions

9 questions
  1. Question 1
    Entry

    Is everything in Ruby an object?

    • Ruby
    Reveal 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.

  2. Question 2
    Entry

    Why Ruby is known as a language of flexibility?

    • Ruby
    Reveal 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.

  3. Question 3
    Entry

    What is an object?

    • Ruby
    Reveal 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.

  4. Question 4
    Entry

    What is a class?

    • Ruby
    Reveal 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.
    
  5. Question 5
    Entry

    What are rubygems?

    • Ruby
    Reveal 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.

  6. Question 6
    Entry

    Is there an equivalent of “continue” in Ruby?

    • Ruby
    Reveal answer

    Yes, it's called next . for i in 0..5 if i < 2 next end puts "Value of local variable is #{i}" end

  7. Question 7
    Entry

    What can you say about an identifier that begins with a capital letter?

    • Ruby
    Reveal answer

    It is a constant.

  8. Question 8
    Entry

    Which core object includes the "Kernel" module?

    • Ruby
    Reveal answer

    Object

  9. Question 9
    Entry

    What is the highest level in the object model?

    • Ruby
    Reveal answer

    BasicObject

Junior questions

30 questions
  1. Question 1
    Junior

    What does it mean to coerce an object? Why would you do it?

    • Ruby
    Reveal 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.

  2. Question 1
    Junior

    What is duck typing and how does it pertain to Ruby?

    • Ruby
    Reveal 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.

  3. Question 2
    Junior

    Are instance methods public or private?

    • Ruby
    Reveal answer

    They are public by default. You can change their visibility using Module#private , Module#protected , or back again using Module#public .

  4. Question 2
    Junior

    What is the difference between nil and false in Ruby?

    • Ruby
    Reveal 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

  5. Question 3
    Junior

    Explain some differences between Ruby and Python

    • Ruby
    Reveal 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.

  6. Question 3
    Junior

    Which of the expressions listed below will result in "false"?

    • Ruby
    Reveal answer

    Problem

    true ? "true" : "false" false ? "true" : "false" nil ? "true" : "false" 1 ? "true" : "false" 0 ? "true" : "false" "false" ? "true" : "false" "" ? "true" : "false"

    [] ? "true" : "false"
    
    ### Solution
    

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

  7. Question 4
    Junior

    Explain each of the following operators and how and when they should be used

    • Ruby
    Reveal 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 the
    

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

  8. Question 5
    Junior

    Can you call a private method outside a Ruby class using its object?

    • Ruby
    Reveal 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"
    
  9. Question 5
    Junior

    What will be the values of ...

    • Ruby
    Reveal answer

    Problem

    Consider the following code: class A

    def self.a(b)
    if b > 0
    b * b
    end
    end
    end
    

    What will be the values of:

    var1 = A.a(0)
    var2 = A.a(2)
    
    ### Solution
    

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

  10. Question 6
    Junior

    What is the difference between nil and false in Ruby?

    • Ruby
    Reveal 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

  11. Question 8
    Junior

    There are three ways to invoke a method in ruby. Can you give me at least two?

    • Ruby
    Reveal 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
    
  12. Question 10
    Junior

    Why might you use #each instead of for/in ?

    • Ruby
    Reveal 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.

  13. Question 10
    Junior

    Are class variables inherited?

    • Ruby
    Reveal 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.

  14. Question 11
    Junior

    What is a predicate in the context of Ruby method naming conventions?

    • Ruby
    Reveal 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
    
  15. Question 11
    Junior

    What is the difference between an Instance Variable and a Class Variable?

    • Ruby
    Reveal 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.

  16. Question 12
    Junior

    What is the difference between private and protected methods?

    • Ruby
    Reveal 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 .

  17. Question 12
    Junior

    Are instance methods public or private?

    • Ruby
    Reveal answer

    They are public by default. You can change their visibility using Module#private , Module#protected , or back again using Module#public .

  18. Question 13
    Junior

    What is the difference between a class variable and a class instance variable?

    • Ruby
    Reveal answer

    Class instance variables are instance variables of a class. Class instance variables cannot be used within instance methods.

  19. Question 13
    Junior

    What is the difference between #== and #=== ?

    • Ruby
    Reveal answer

    #== performs the generic comparison while #=== performs case equality comparison and is useful for providing meaningful semantics in case statements.

  20. Question 14
    Junior

    How might you specify a default value for a hash?

    • Ruby
    Reveal 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 .

  21. Question 14
    Junior

    What are two uses of the splat operator?

    • Ruby
    Reveal answer

    Explode or expand the elements of an array. Collect arguments of a parameter list into an array.

  22. Question 15
    Junior

    Is Ruby a strongly typed or a weakly typed language?

    • Ruby
    Reveal answer

    Strongly typed since an object's type is checked before an operation is performed on it.

  23. Question 15
    Junior

    Why might you use Hash#fetch over Hash#[] when querying values in a hash?

    • Ruby
    Reveal answer

    Hash#fetch provides options for handling the case where a key does not exist in the hash.

  24. Question 16
    Junior

    What is a module? Can you tell me the difference between classes and modules?

    • Ruby
    Reveal 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
    
  25. Question 16
    Junior

    Why are symbols typically used as hash keys instead of strings?

    • Ruby
    Reveal 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.

  26. Question 17
    Junior

    What does it mean to coerce an object? Why would you do it?

    • Ruby
    Reveal 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.

  27. Question 18
    Junior

    Is Ruby a statically typed or a dynamically typed language?

    • Ruby
    Reveal answer

    Dynamically typed since type checking is done at runtime.

  28. Question 19
    Junior

    How do you remove nil values in array using ruby?

    • Ruby
    Reveal answer

    Array#compact removes nil values.

    >> [nil,123,nil,"test"].compact
    => [123, "test"]
    
  29. Question 19
    Junior

    What is a DSL and how does it pertain to Ruby?

    • Ruby
    Reveal 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.

  30. Question 20
    Junior

    Explain redo statement in Ruby

    • Ruby
    Reveal 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
  1. Question 1
    Mid

    What is the difference between Proc invocation and lambda invocation?

    • Ruby
    Reveal 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.

  2. Question 1
    Mid

    What are two uses of ranges?

    • Ruby
    Reveal answer

    comparison iteration

  3. Question 2
    Mid

    What is the difference between Array#map and Array#each ?

    • Ruby
    Reveal 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

  4. Question 4
    Mid

    What is the difference between calling "super" and calling "super()"

    • Ruby
    Reveal 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.

  5. Question 4
    Mid

    What is the difference between Kernel#require and Kernel#load ?

    • Ruby
    Reveal 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.

  6. Question 5
    Mid

    How is the invocation of a private method different than the invocation of a public method from within its defining class?

    • Ruby
    Reveal 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 .

  7. Question 6
    Mid

    What is a Proc?

    • Ruby
    Reveal 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>
    
  8. Question 6
    Mid

    What is an iterator?

    • Ruby
    Reveal 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.

  9. Question 7
    Mid

    Why can you safely use a string as a hash key, even though a string is mutable?

    • Ruby
    Reveal answer

    Because the interpreter makes a private copy of a string used as a hash key.

  10. Question 7
    Mid

    What does self mean?

    • Ruby
    Reveal 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.

  11. Question 7
    Mid

    What are some disadvantages of a case statement versus repeated elsif statements?

    • Ruby
    Reveal 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.

  12. Question 8
    Mid

    What does a bang ! at the end of a method signify?

    • Ruby
    Reveal answer

    That it should be with caution. Methods with this naming convention typically perform a *mutation on the receiver object.

  13. Question 8
    Mid

    Explain this ruby idiom: a ||= b

    • Ruby
    Reveal 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
    
  14. Question 8
    Mid

    What is the difference between #== and #eql? ?

    • Ruby
    Reveal 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.

  15. Question 9
    Mid

    Describe a closure in Ruby

    • Ruby
    Reveal 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 .

  16. Question 9
    Mid

    Can you tell me the three levels of method access control for classes and modules? What do they imply about the method?

    • Ruby
    Reveal 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_method
    

    puts "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>
    
  17. Question 9
    Mid

    Why can you safely use a string as a hash key, even though a string is mutable?

    • Ruby
    Reveal answer

    Because the interpreter makes a private copy of a string used as a hash key.

  18. Question 10
    Mid

    Describe a closure in Ruby

    • Ruby
    Reveal 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 .

  19. Question 10
    Mid

    Can you tell me the three levels of method access control for classes and modules? What do they imply about the method?

    • Ruby
    Reveal 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_method
    

    puts "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>
    
  20. Question 11
    Mid

    Why might you want to avoid using string literals within loops?

    • Ruby
    Reveal answer

    A new object is created for every string literal even when the values are identical. Consider using variables or symbols instead.

  21. Question 11
    Mid

    What does self mean?

    • Ruby
    Reveal 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.

  22. Question 12
    Mid

    What is the main difference between procs and lambdas?

    • Ruby
    Reveal 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.

  23. Question 13
    Mid

    What is the difference between Module#remove_method and Module#undef_method ?

    • Ruby
    Reveal 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.

  24. Question 14
    Mid

    Why might you want to alias a method?

    • Ruby
    Reveal 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.

  25. Question 15
    Mid

    What does a bang ! at the end of a method signify?

    • Ruby
    Reveal answer

    That it should be with caution. Methods with this naming convention typically perform a *mutation on the receiver object.

  26. Question 16
    Mid

    How does block invocation differ from method invocation?

    • Ruby
    Reveal 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.

  27. Question 17
    Mid

    When might you use the do / end syntax versus using the curly bracket syntax for a block?

    • Ruby
    Reveal 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.

  28. Question 18
    Mid

    What is the difference between throw/catch and raise/rescue ?

    • Ruby
    Reveal 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.

  29. Question 19
    Mid

    What is the difference between #== and #equal? ?

    • Ruby
    Reveal 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.

  30. Question 20
    Mid

    Explain redo vs. retry usage

    • Ruby
    Reveal 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
  1. Question 3
    Senior

    Write a single line of Ruby code that prints the Fibonacci sequence of any length as an array.

    • Ruby
    Reveal 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 result
    

    to the end of fib . Note: inject is an alias of reduce

  2. Question 10
    Senior

    Is a block an object?

    • Ruby
    Reveal answer

    No. A block is a syntactic structure of the interpreter. A block can be converted to a Proc object.

  3. Question 11
    Senior

    What happens if a block is passed two arguments but only accepts one argument?

    • Ruby
    Reveal answer

    Nothing. Only the first argument will be passed to the block.

  4. Question 12
    Senior

    Why doesn't Ruby support method overloading?

    • Ruby
    Reveal 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.

  5. Question 12
    Senior

    Is a block an object?

    • Ruby
    Reveal answer

    No. A block is a syntactic structure of the interpreter. A block can be converted to a Proc object.

  6. Question 13
    Senior

    Is a method an object?

    • Ruby
    Reveal answer

    No, however, a Method object is of course, an object.

  7. Question 13
    Senior

    When might you encounter a LocalJumpError ?

    • Ruby
    Reveal 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.

  8. Question 14
    Senior

    When might you encounter a LocalJumpError ?

    • Ruby
    Reveal 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.

  9. Question 14
    Senior

    What is the primary difference in these two code snippets?

    • Ruby
    Reveal answer

    Problem

    // Java
    public boolean isEmpty(String s) {
      return s.length() == 0;
    }
    # ruby
    def empty?(s)
    return s.size == 0
    end
    
    ### Solution
    

    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.

  10. Question 15
    Senior

    What happens to a constant which is not assigned?

    • Ruby
    Reveal answer

    It does not exist.

  11. Question 15
    Senior

    Write a single line of Ruby code that prints the Fibonacci sequence of any length as an array.

    • Ruby
    Reveal 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 result
    

    to the end of fib . Note: inject is an alias of reduce

  12. Question 16
    Senior

    What is an eigenclass?

    • Ruby
    Reveal answer

    An anonymous class associated with an object. An object's singleton methods are instance methods of its associated eigenclass.

  13. Question 17
    Senior

    What is the difference between Object#dup and #clone ?

    • Ruby
    Reveal answer

    #clone copies the frozen state of an object and any singleton methods of an object while Object#dup does neither.

  14. Question 18
    Senior

    What is the difference between BasicObject#instance_eval and BasicObject#instance_exec ?

    • Ruby
    Reveal 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
  1. Question 4
    Expert

    What is the differnece between extend and include in ruby?

    • Ruby
    Reveal 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.