Category Ruby quiz (intermediate)

Ruby Quiz (Intermediate) #6

Question What would be the output of this code snippet?   Solution The output is “nil”. Here is the reason why, taken from Programming Ruby 2nd edition (p. 86): [W]ritable attributes have a hidden gotcha. Normally, methods within a class can invoke other methods in the same class and its superclasses in functional form (that is, with […]

Ruby Quiz (Intermediate) #5

Question Say you have this simple home-made (and not very useful) class: Write some code in order to prove that instance methods are defined in the singleton class of an instance, and that class methods are defined in the class’ metaclass (the singleton class for a class).   Solution All we need is a way […]

Ruby quiz (intermediate) #4

Question What will be the output of the following code?   Solution The output is as follows: my string The Decorator#to_s method, which is (unsuccessfully) trying to override String#to_s, will be defined in the singleton class of an instance of the Decorator class, upon instantiation. However, when the Decorator#initialize method gets called during the instantiation, […]

Ruby quiz (intermediate) #3

Question We are familiar with Hash.new in order to define a Hash. What are the 2 other ways to initialize a Hash? Solution See Ruby doc on Hash.new for more info. Thanks to this post from Ilya Grigorik for the inspiration!

Ruby quiz (intermediate) #2

Question What is the difference between the private access modifier in Java versus Ruby? Solution In Ruby, you can only call a private method from within the class in which it is defined. The receiver of a private method needs to be the class in which that private method was defined. In other words: If […]

Ruby quiz (intermediate) #1

Question write code so that you would add some scrolling behavior using the decorator pattern, in two flavors: instance-specific (adding behavior to a specific instance) class extension (adding behavior to all future instantiations) with the following code:   Solution produces: kind of Scrollable? false kind of Scrollable? true kind of Scrollable? true