Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It started off as this:</p> <pre><code>class Tree include Comparable attr_reader :data # Create a new node with one initial data element def initialize(data=nil) @data = data end # Spaceship operator. Comparable uses this to generate # &lt;, &lt;=, ==, =&gt;, &gt;, and between? def &lt;=&gt;(other) @data.to_s &lt;=&gt; other.data.to_s end # Insert an object into the subtree including and under this Node. # First choose whether to insert into the left or right subtree, # then either create a new node or insert into the existing node at # the head of that subtree. def insert(data) if !@data @data = data else node = (data.to_s &lt; @data.to_s) ? :@left : :@right create_or_insert_node(node, data) end end # Sum all the numerical values in this tree. If this data object is a # descendant of Numeric, add @data to the sum, then descend into both subtrees. def total sum = 0 sum += @data if (@data.is_a? Numeric) sum += [@left, @right].map{|e| e.total rescue 0}.inject(0){|a,v|a+v} sum end # Convert this subtree to a String. # Format is: &lt;tt&gt;\&lt;data,left_subtree,right_subtree&gt;&lt;/tt&gt;. # Non-existant Nodes are printed as &lt;tt&gt;\&lt;&gt;&lt;/tt&gt;. def to_s subtree = lambda do |tree| tree.to_s.empty? ? "&lt;&gt;" : tree end "&lt;#{@data},#{subtree[@left]},#{subtree[@right]}&gt;" end private ############################################################ # Given a variable-as-symbol, insert data into the subtree incl. and under this node. def create_or_insert_node(nodename, data) if instance_variable_get(nodename).nil? instance_variable_set(nodename, Tree.new(data)) else instance_variable_get(nodename).insert(data) end end end </code></pre> <p>I think I actually broke it when I was shortening it down. The nine-line version doesn't quite work. I had fun regardless. :P</p> <p>This was my favourite part:</p> <pre><code>def initialize*d;@d,=d;end </code></pre> <p>This is acutally making use of parallel assignment to save a couple characters. You could expand this line to:</p> <pre><code>def initialize(*d) @d = d[0] 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