Added test for Hash default value. Developers often forget about using it.
[ruby_koans.git] / koans / about_hashes.rb
1 require File.expand_path(File.dirname(__FILE__) + '/edgecase')
2
3 class AboutHashes < EdgeCase::Koan
4   def test_creating_hashes
5     empty_hash = Hash.new
6     assert_equal __, empty_hash.class
7     assert_equal({}, empty_hash)
8     assert_equal __, empty_hash.size
9   end
10
11   def test_hash_literals
12     hash = { :one => "uno", :two => "dos" }
13     assert_equal __, hash.size
14   end
15
16   def test_accessing_hashes
17     hash = { :one => "uno", :two => "dos" }
18     assert_equal __, hash[:one]
19     assert_equal __, hash[:two]
20     assert_equal __, hash[:doesnt_exist]
21   end
22
23   def test_changing_hashes
24     hash = { :one => "uno", :two => "dos" }
25     hash[:one] = "eins"
26
27     expected = { :one => __, :two => "dos" }
28     assert_equal __, expected == hash
29
30     # Bonus Question: Why was "expected" broken out into a variable
31     # rather than used as a literal?
32   end
33
34   def test_hash_is_unordered
35     hash1 = { :one => "uno", :two => "dos" }
36     hash2 = { :two => "dos", :one => "uno" }
37
38     assert_equal __, hash1 == hash2
39   end
40
41   def test_hash_keys
42     hash = { :one => "uno", :two => "dos" }
43     assert_equal __, hash.keys.size
44     assert_equal __, hash.keys.include?(:one)
45     assert_equal __, hash.keys.include?(:two)
46     assert_equal __, hash.keys.class
47   end
48
49   def test_hash_values
50     hash = { :one => "uno", :two => "dos" }
51     assert_equal __, hash.values.size
52     assert_equal __, hash.values.include?("uno")
53     assert_equal __, hash.values.include?("dos")
54     assert_equal __, hash.values.class
55   end
56
57   def test_combining_hashes
58     hash = { "jim" => 53, "amy" => 20, "dan" => 23 }
59     new_hash = hash.merge({ "jim" => 54, "jenny" => 26 })
60
61     assert_equal __, hash != new_hash
62
63     expected = { "jim" => __, "amy" => 20, "dan" => 23, "jenny" => __ }
64     assert_equal __, expected == new_hash
65   end
66
67   def test_default_value
68     hash1 = Hash.new
69     hash1[:one] = 1
70
71     assert_equal __, hash1[:one]
72     assert_equal __, hash1[:two]
73
74     hash2 = Hash.new("dos")
75     hash2[:one] = 1
76
77     assert_equal __, hash2[:one]
78     assert_equal __, hash2[:two]
79   end
80 end