1 require File.expand_path(File.dirname(__FILE__) + '/edgecase')
3 class AboutHashes < EdgeCase::Koan
4 def test_creating_hashes
6 assert_equal __(Hash), empty_hash.class
7 assert_equal({}, empty_hash) # __
8 assert_equal __(0), empty_hash.size
11 def test_hash_literals
12 hash = { :one => "uno", :two => "dos" }
13 assert_equal __(2), hash.size
16 def test_accessing_hashes
17 hash = { :one => "uno", :two => "dos" }
18 assert_equal __("uno"), hash[:one]
19 assert_equal __("dos"), hash[:two]
20 assert_equal __(nil), hash[:doesnt_exist]
23 def test_accessing_hashes_with_fetch
24 hash = { :one => "uno" }
25 assert_equal "uno", hash.fetch(:one)
26 assert_raise(___(IndexError)) do
27 hash.fetch(:doesnt_exist)
32 # Why might you want to use #fetch instead of #[] when accessing hash keys?
35 def test_changing_hashes
36 hash = { :one => "uno", :two => "dos" }
39 expected = { :one => __("eins"), :two => "dos" }
40 assert_equal __(true), expected == hash
42 # Bonus Question: Why was "expected" broken out into a variable
43 # rather than used as a literal?
46 def test_hash_is_unordered
47 hash1 = { :one => "uno", :two => "dos" }
48 hash2 = { :two => "dos", :one => "uno" }
50 assert_equal __(true), hash1 == hash2
54 hash = { :one => "uno", :two => "dos" }
55 assert_equal __(2), hash.keys.size
56 assert_equal __(true), hash.keys.include?(:one)
57 assert_equal __(true), hash.keys.include?(:two)
58 assert_equal __(Array), hash.keys.class
62 hash = { :one => "uno", :two => "dos" }
63 assert_equal __(2), hash.values.size
64 assert_equal __(true), hash.values.include?("uno")
65 assert_equal __(true), hash.values.include?("dos")
66 assert_equal __(Array), hash.values.class
69 def test_combining_hashes
70 hash = { "jim" => 53, "amy" => 20, "dan" => 23 }
71 new_hash = hash.merge({ "jim" => 54, "jenny" => 26 })
73 assert_equal __(true), hash != new_hash
75 expected = { "jim" => __(54), "amy" => 20, "dan" => 23, "jenny" => __(26) }
76 assert_equal __(true), expected == new_hash
79 def test_default_value
83 assert_equal __(1), hash1[:one]
84 assert_equal __(nil), hash1[:two]
86 hash2 = Hash.new("dos")
89 assert_equal __(1), hash2[:one]
90 assert_equal __("dos"), hash2[:two]
93 def test_default_value_is_the_same_object
99 assert_equal __(["uno", "dos"]), hash[:one]
100 assert_equal __(["uno", "dos"]), hash[:two]
101 assert_equal __(["uno", "dos"]), hash[:three]
103 assert_equal __(true), hash[:one].object_id == hash[:two].object_id
106 def test_default_value_with_block
107 hash = Hash.new {|hash, key| hash[key] = [] }
112 assert_equal __(["uno"]), hash[:one]
113 assert_equal __(["dos"]), hash[:two]
114 assert_equal __([]), hash[:three]