Dictionary = Hash?

后端 未结 4 2143
我在风中等你
我在风中等你 2021-02-04 04:10

Is a dictionary basically just a hash table?

Also bonus: In the Ruby code \"Hash.new {0}\" what is the \"{0}\" at the end for?

4条回答
  •  眼角桃花
    2021-02-04 04:45

    The words table, dictionary and map are often used synonymously (in the context of data structures). A hash table/hash map is one kind of table/dictionary/map.

    The {0} is a block (anonymous function) which ignores its argument and returns the number 0. The block given to Hash.new is called to produce a default value when a key is not found in the hash map.

    I.e. if I do h = Hash.new {0} and then h["key that does not exist"], I get back 0, instead of nil (which I'd get without the {0}). Note that in this case where the default value is immutable and does not depend on the key, you don't need to use the block form of Hash.new, you can just do Hash.new(0) to set 0 as the default value.

提交回复
热议问题