Skip to content

Commit

Permalink
add Hash.of
Browse files Browse the repository at this point in the history
  • Loading branch information
quix committed Aug 23, 2009
1 parent f69f66f commit ceec2fb
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 7 deletions.
1 change: 1 addition & 0 deletions lib/quix.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

require 'quix/ext/array'
require 'quix/ext/dir'
require 'quix/ext/hash'
require 'quix/ext/kernel'
require 'quix/ext/module'
require 'quix/ext/object'
Expand Down
6 changes: 6 additions & 0 deletions lib/quix/ext/hash.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@

class Hash
class << self
def of(klass, *args)
new { |hash, key| hash[key] = klass.new(*args) }
end
end

def key_sorted_each_pair
keys.sort.each { |key|
yield key, self[key]
Expand Down
18 changes: 18 additions & 0 deletions test/test_hash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,22 @@ def test_hash
}
assert_equal %w[y x z], memo
end

def test_hash_of_array
h = Hash.of Array
assert h.empty?
assert h[:x].is_a?(Array)
assert_block { not h.empty? }
h[:x] << 33
assert_equal [33], h[:x]
end

def test_hash_of_hashes
h = Hash.of Hash
assert h.empty?
assert h[:x].is_a?(Hash)
assert_block { not h.empty? }
h[:x][:y] = 33
assert_equal 33, h[:x][:y]
end
end
16 changes: 9 additions & 7 deletions test/test_object.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,21 @@ def test_singleton_class
end

def test_tap
ret = "a".tap { |t|
assert_equal "a", t
value = Object.new
result = value.tap { |t|
assert_equal value.object_id, t.object_id
nil
}
assert_equal "a", ret
assert_equal value.object_id, result.object_id
end

def test_let
ret = "a".let { |t|
assert_equal "a", t
"b"
value = Object.new
result = value.let { |t|
assert_equal value.object_id, t.object_id
"z"
}
assert_equal "b", ret
assert_equal "z", result
end

def test_try
Expand Down

0 comments on commit ceec2fb

Please sign in to comment.