Ruby default hash values ​​(Rubykoans.com & # 8594; about_hashes.rb)

I am browsing about_hashes.rb from RubyKoans . 1 exercise puzzled me:

def test_default_value hash1 = Hash.new hash1[:one] = 1 assert_equal 1, hash1[:one] #ok assert_equal nil, hash1[:two] #ok hash2 = Hash.new("dos") hash2[:one] = 1 assert_equal 1, hash2[:one] #ok assert_equal "dos", hash2[:two] #hm? end 

I assume that Hash.new ("dos") makes "dos" the default answer for all non-existent keys. I'm right?

+6
source share
2 answers

Yes, you're right, it seems that there is an error in the ruby ​​koans, hash2[:two] will return "dos"

Take a look at the hash.new documentation

new β†’ new_hash
new (obj) β†’ new_hash
new {| hash key | block} β†’ new_hash

Returns a new empty hash. If after this hash there is a key that does not match the hash record, the return value depends on the style of the new one used to create the hash. First of all, access returns nil. If obj is specified, this single object will be used for all default values . If a block is specified, it will call with a hash object and a key and return the default value. This blocks the responsibility for storing the value in the hash, if required.

Sidenote: you can confirm your expectations in such cases by running real code or by running a couple of lines in irb or pry (I recommend pry).

+9
source

Original koan:

 def test_default_value hash1 = Hash.new hash1[:one] = 1 assert_equal __, hash1[:one] assert_equal __, hash1[:two] hash2 = Hash.new("dos") hash2[:one] = 1 assert_equal __, hash2[:one] assert_equal __, hash2[:two] end 

The error is not in koan, but in the completed statement:

 assert_equal nil, hash2[:two] #hm? 

... it should be

 assert_equal "dos", hash2[:two] #hm? 
+4
source

Source: https://habr.com/ru/post/907934/


All Articles