Dictionary = Hash?

后端 未结 4 2141
我在风中等你
我在风中等你 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 05:04

    In Ruby a Hash is a key, value store

    h = Hash.new
    h['one'] = 1
    h['one'] #=> 1
    h['two'] #=> nil
    

    the {0} is a block that will be evaluated if you where to call a Key that did not exist, it's like a default value.

    h = Hash.new {0}
    h['one'] #=> 0
    h = Hash.new {|hash,key| "#{key} has Nothing"}
    h['one'] #=> "one has Nothing"
    

提交回复
热议问题