Recipe 5.5. Using an Array or Other Modifiable Object as a Hash Key
Suppose you want a reliably hashable Array class. If you want this behavior universally, you can reopen the Array class and redefine hash to give you the new behavior. But it's safer to define a subclass of Array that implements a reliable-hashing mixin, and to use that subclass only for the Arrays you want to use as hash keys:
module ReliablyHashable
def hash
return object_id
end
end
class ReliablyHashableArray < Array
include ReliablyHashable
end
It's now possible to keep track of the jewels:
coordinates = ReliablyHashableArray.new([10,5])
treasure_map = { coordinates => 'jewels' }
treasure_map[coordinates] # => "jewels"
# Add a z-coordinate to indicate how deep the treasure is buried.
coordinates.push(-5)
treasure_map[coordinates] # => "jewels"
Ruby performs hash lookups using not the key object itself but the object's hash code (an integer obtained from the key by calling its hash method). The default implementation of hash, in Object, uses an object's internal ID as its hash code. Array, Hash, and String override this method to provide different behavior.
分享到:
相关推荐
"cookbook-zh-CN.md"文件很可能是这本书的主要文本部分,里面详细列举了各种使用PySimpleGUI的技巧和实践案例。每个章节通常会介绍一个特定的功能或概念,并配有相应的代码示例。通过阅读和实践这些例子,开发者可以...
python-machine-learning-cookbook-preprocessing oreilly 英文 epub格式
If you are a beginner or an intermediate Linux user who wants to master the skill of quickly writing scripts and automate tasks without reading the entire man pages, then this book is for you....
标题“coverage-cookbook-complete-verification-academy”表明这是一本关于覆盖度(coverage)的食谱手册,隶属于Cadence Academy的官方文件。这种手册通常包含一系列经过精心设计的指导方案,旨在帮助读者理解和...
《CMake Cookbook》是关于构建、测试和打包模块化软件的专业指南,专注于现代CMake工具的使用。本书由Radovan Bast和Roberto Di Remigio合著,旨在帮助读者掌握CMake这一强大的跨平台构建系统。 CMake是一个开源的...
Programming ArcGIS with Python Cookbook - Second Edition, mobi格式
Programming ArcGIS with Python Cookbook - Second Edition,epub格式
It covers both routing basics as well as an array of advanced routing concepts unique to Angular 2. Chapter 7, Services, Dependency Injection, and NgModule, describes the new and improved dependency...
Unity Game Development Cookbook - Paris Buttfield-AddisonUnity Game Development Cookbook - Paris Buttfield-Addison
docker run -tid -p <port>:80 apachecn0/pandas-cookbook-code-notes # 访问 http://localhost:{port} 查看文档 PYPI pip install pandas-cookbook-code-notes pandas-cookbook-code-notes # 访问 ...
"NGINX Cookbook 高性能负载平衡高级配方" NGINX Cookbook 是一本专门介绍 NGINX 高性能负载平衡的书籍,书中涵盖了 NGINX 的高级配方和使用技巧,可以帮助读者快速搭建高性能的负载平衡系统。 GeoIP 模块和数据库...
Lott -- Modern Python Cookbook -- 2016 -- code.7z
Aggarwal -- Flask Framework Cookbook -- 2014 -- code.7z
Subramanian -- Python Data Science Cookbook -- 2015 -- code.7z
Fine -- Python 2.6 Graphics Cookbook -- 2010 -- code.7z