Note that there are some explanatory texts on larger screens.

plurals
  1. POOptimal Design of a Ruby Data Structures Library
    text
    copied!<p>I am working with data structures fundamentals in Ruby for learning at the CS sophomore/junior level. </p> <p>My question: Given the following code, does anyone see any design issues with this approach to a data structures library in Ruby? Especially the Module#abstract_method. Is it okay to do this in terms of duck typing philosophy? Does this make the code clearer for people from static languages and give some semblance of an interface?</p> <pre><code>class Module def abstract_method(symbol) module_eval &lt;&lt;-"end_eval" def #{symbol.id2name}(*args) raise MethodNotImplementedError end end_eval end end class AbstractObject &lt; Object abstract_method :compare_to protected :compare_to class MethodNotImplementedError &lt; StandardError; end def initialize super end include Comparable def &lt;=&gt;(other) if is_a?(other.class) return compare_to(other) elsif other.is_a?(self.class) return -other.compare_to(self) else return self.class &lt;=&gt; other.class end end end # methods for insertion/deletion should be provided by concrete implementations as this behavior # is unique to the type of data structure. Also, concrete classes should override purge to discard # all the contents of the container class Container &lt; AbstractObject include Enumerable def initialize super @count = 0 end attr_reader :count alias :size :count # should return an iterator abstract_method :iter # depends on iterator object returned from iter method # layer of abstraction for how to iterate a structure def each i = iter while i.more? yield i.succ end end # a visitor provides another layer of abstraction for additional # extensible and re-usable traversal operations def accept(visitor) raise ArgumentError, "Argument must be a visitor" unless visitor.is_a?(Visitor) each do |obj| break if visitor.done? visitor.visit(obj) end end # expected to over-ride this in derived classes to clear container def purge @count = 0 end def empty? count == 0 end def full? false end def to_s s = "" each do |obj| s &lt;&lt; ", " if not s.empty? s &lt;&lt; obj.to_s end self.class + "{" + s + "}" end end class List &lt; Container def initialize super end def compare_to(obj) "fix me" end end </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload