Permalink
Browse files

add the old version that this code was refactored from, as a reference

  • Loading branch information...
1 parent 340c075 commit 1b3abcbb23036439d3ea469ae70e04cc57eae4d5 @JoshCheek JoshCheek committed Apr 28, 2011
Showing with 37 additions and 0 deletions.
  1. +1 −0 self-referential-hash/Readme.mdown
  2. +36 −0 self-referential-hash/rhash.before_refactoring.rb
View
1 self-referential-hash/Readme.mdown
@@ -3,6 +3,7 @@ Description
Code to create a hash that lets you declare one key to reference another, used to answer [this](http://www.ruby-forum.com/topic/1592736) ruby-talk post.
+Adding this mostly because I really enjoyed refactoring it. Compare the before version, which requires lots of comments to explain, and has complicated nested conditionals, and the after version, where any comments would be redundant. Might turn that into an assignment for Ruby Kickstart or something.
---------------------------------------
View
36 self-referential-hash/rhash.before_refactoring.rb
@@ -0,0 +1,36 @@
+class RHash
+
+ def initialize
+ @hash = Hash.new
+ @references = Hash.new
+ end
+
+ def [](key)
+ return nil unless @references.has_key? key # no endpoint
+ actual_key = @references[key]
+ return @hash[actual_key] if actual_key == key # this is the endpoint
+ return self[actual_key] # recursively follow the references
+ end
+
+ def []=(key,value)
+ actual_key = @references[key]
+ if @references.has_key? key # if it is part of a reference chain
+ if actual_key == key
+ @hash[key] = value # if it is an endpoint update its value
+ else
+ self[actual_key] = value # if it is not an endpoint, recursively set the endpoint to the value
+ end
+ else
+ @references[key] = key # if it is not part of a reference chain, make it an endpoint in its own chain
+ @hash[key] = value
+ end
+ end
+
+ def refer(references)
+ references.each do |from, to|
+ @references[from] = to # update the reference
+ @hash.delete from unless from == to # remove orphaned data
+ end
+ end
+
+end

0 comments on commit 1b3abcb

Please sign in to comment.