0
\$\begingroup\$

I want to make a Ruby nested hash table class to avoid repeating ugly code and to keep my programs as true to the OOP paradigm as I can. Are there any ways to make this class definition smaller and/or simpler?

To clarify, the class essentially creates an arbitrarily-deep hash table. For example, if you had a NestedHash object called foo, you could write foo[:a][:b][:c] = 1.

class NestedHash
 include Enumerable
 def initialize
 @outer = Hash.new { |hash, key| hash[key] = Hash.new(&hash.default_proc) }
 end
 def keys
 @outer.keys
 end
 def values
 @outer.values
 end
 def [](key)
 @outer[key]
 end
 def []=(key, value)
 @outer[key] = value
 end
 def each
 @outer.each { |key, value| yield(key, value) }
 end
end
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Mar 2, 2016 at 1:05
\$\endgroup\$
0

1 Answer 1

2
\$\begingroup\$

So really, the meat of your whole program is in the single line of the constructor. The rest of it is just forwarding methods to @outer. So we should do that explicitly:

require 'forwardable'
class NestedHash
 extend Forwardable
 include Enumerable
 def_delegators :@outer, :[], :[]=, :keys, :values, :each
 def initialize
 @outer = Hash.new { |hash, key| hash[key] = Hash.new(&hash.default_proc) }
 end
end
h = NestedHash.new
h[:a][:b] = 99
p h[:a][:b] #=> 99

Keep in mind that you can get the same effect also by just doing:

module NestedHash
 def self.create
 Hash.new { |hash, key| hash[key] = Hash.new(&hash.default_proc) }
 end
end

and use it like:

h = NestedHash.create
answered Mar 2, 2016 at 20:56
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.