Ruby Design Patterns Interview Questions

Suppose you have a class that performs several expensive calculations. However, during the lifetime of an object, the result of the expensive calculation won't change. Therefore, you wish to ensure that each calculation is performed only once, and that result is cached. A simple technique for this would be as follows:

class Calculator
    def expensive_calc_one
        return @result1 unless @result1.nil?
       @result1 = # Do very expensive calculation.
    end

   def expensive_calc_two
        return @result2 unless @result2.nil?
       @result2 = # Do very expensive calculation.
    end
end

If this class contained many such expensive calculations, this memoization technique would become repetitive. Can you come up with a framework that reduces this repetition by allowing one to simply mark a method as memoized and no longer have to worry about manually handling the caching?

Bonus points: There is a flaw in the simple technique. Under one set of circumstances the caching will fail and repeated calls to expensive_calc_one will result in the expensive calculation being executed again and gain. When would this occur?

Suppose you have a web form that allows users to upload JPG, GIF or PNG images. Before you store the images in your system, you want to convert them all to the JPG format. Design an image converter API. Sketch out all classes and interfaces that are involved.

Note: the actual code necessary to convert a JPG image to a GIF image is not the point. Just place a comment at the appropriate location where the actual conversion should occur.