字典=哈希? [英] Dictionary = Hash?

查看:153
本文介绍了字典=哈希?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个字典基本上只是一个哈希表?



另外还有:在Ruby代码Hash.new {0}中有什么是{0}

解决方案

表,字典和地图这些词通常被同义使用(在数据结构的上下文中)。哈希表/散列图是一种表/字典/地图。



{0} 是一个阻止(匿名函数),忽略其参数并返回数字0.给定为 Hash.new 的块被调用以产生默认值,当在哈希图。



即如果我执行 h = Hash.new {0} 然后 h [不存在的键] 我回到0,而不是 nil (没有$ code> {0} )。请注意,在这种情况下,默认值是不可变的,不依赖于密钥,您不需要使用 Hash.new 的块形式,您只需do Hash.new(0)将0设置为默认值。


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?

解决方案

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.

这篇关于字典=哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆