Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Added support for arbitrary depth deep hashes (issue #1)

  • Loading branch information...
commit a510bb35e73f0d6ea61a9263c81593820933c362 1 parent ab4e950
Caleb Spare authored July 07, 2011
12  lib/deep_hash.rb
... ...
@@ -1,11 +1,15 @@
1 1
 require "deep_hash/version"
2 2
 
3 3
 class Hash
4  
-  def self.deep(depth, &block)
5  
-    raise "Need non-negative depth" if depth < 0
6  
-    if depth.zero?
7  
-      return block_given? ? Hash.new { |k, v| k[v] = block.call } : {}
  4
+  def self.deep(depth = nil, &block)
  5
+    raise "Need a number for depth" unless depth.nil? || depth.respond_to?(:to_i)
  6
+    if depth.nil?
  7
+      raise "Cannot use a block with nil depth." if block_given?
  8
+      return Hash.new { |k, v| k[v] = Hash.deep(nil) }
8 9
     end
  10
+    depth = depth.to_i
  11
+    raise "Need non-negative depth" if depth < 0
  12
+    return block_given? ? Hash.new { |k, v| k[v] = block.call } : {} if depth.zero?
9 13
     Hash.new { |k, v| k[v] = Hash.deep(depth - 1, &block) }
10 14
   end
11 15
 end
2  lib/deep_hash/version.rb
... ...
@@ -1,3 +1,3 @@
1 1
 module DeepHash
2  
-  VERSION = "0.0.1"
  2
+  VERSION = "0.0.2"
3 3
 end
14  test/deep_hash_test.rb
@@ -47,5 +47,19 @@ def assert_expected_hash(expected, actual)
47 47
         assert_expected_hash({ :a => { 0 => 5, 1 => "foobar" }, :b => { 0 => "foobar" } }, hash)
48 48
       end
49 49
     end
  50
+
  51
+    context "with nil depth" do
  52
+      should "raise an error if a block is given" do
  53
+        assert_raises(RuntimeError) { Hash.deep {} }
  54
+      end
  55
+
  56
+      should "create an arbitrary depth default hash" do
  57
+        hash = Hash.deep
  58
+        hash[0][0][0] = 1
  59
+        hash[0][1] = 2
  60
+        hash[1] = :bar
  61
+        assert_expected_hash({ 0 => { 0 => { 0 => 1 }, 1 => 2 }, 1 => :bar }, hash)
  62
+      end
  63
+    end
50 64
   end
51 65
 end

0 notes on commit a510bb3

Please sign in to comment.
Something went wrong with that request. Please try again.