Creating a Hash with a Default Value
first_letter_hash = Hash.new { |hash, key| hash[key] = [] }
text.split(/\W+/).each { |word| first_letter_hash[word[0,1].downcase] << word }
first_letter_hash
# => {"m"=>["mainly"], "p"=>["plain"], "f"=>["falls"], "r"=>["rain"],
# "s"=>["Spain"], "i"=>["in", "in"], "t"=>["The", "the"]}
first_letter_hash["m"]
# => ["mainly"]
When a letter can't be found in the hash, Ruby calls the block passed into the Hash constructor. That block puts a new array into the hash, using the missing letter as the key. Now the letter is bound to a unique array, and words can be added to that array normally.
Note that if you want to add the array to the hash so it can be used later, you must assign it within the block of the Hash constructor. Otherwise you'll get a new, empty array every time you access first_letter_hash["m"]. The words you want to append to the array will be lost.
分享到:
相关推荐
"cookbook-zh-CN.md"文件很可能是这本书的主要文本部分,里面详细列举了各种使用PySimpleGUI的技巧和实践案例。每个章节通常会介绍一个特定的功能或概念,并配有相应的代码示例。通过阅读和实践这些例子,开发者可以...
Odoo 14 Development Cookbook - Fourth Edition(ebook-eglish) 代码
python-machine-learning-cookbook-preprocessing oreilly 英文 epub格式
Programming ArcGIS with Python Cookbook - Second Edition, mobi格式
Programming ArcGIS with Python Cookbook - Second Edition,epub格式
标题“coverage-cookbook-complete-verification-academy”表明这是一本关于覆盖度(coverage)的食谱手册,隶属于Cadence Academy的官方文件。这种手册通常包含一系列经过精心设计的指导方案,旨在帮助读者理解和...
The 2019 edition of this popular cookbook provides more than 80 practical recipes to help you set up and use this open source server to solve problems in various use cases. For professionals who ...
《CMake Cookbook》是关于构建、测试和打包模块化软件的专业指南,专注于现代CMake工具的使用。本书由Radovan Bast和Roberto Di Remigio合著,旨在帮助读者掌握CMake这一强大的跨平台构建系统。 CMake是一个开源的...
Linux Shell Scripting Cookbook - Third Edition by Clif Flynt English | 29 May 2017 | ASIN: B01N80F75Z | 552 Pages | AZW3 | 1.36 MB Do amazing things with the shell About This Book Become an expert ...
Bioinformatics-with-Python-Cookbook-Learn-how-to-use-modern-Python-bioinformatics-libraries-and-applications-to-do-cutting-edge-research-in-computational-biology.pdf
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 # 访问 ...
Unity Game Development Cookbook - Paris Buttfield-AddisonUnity Game Development Cookbook - Paris Buttfield-Addison
Lott -- Modern Python Cookbook -- 2016 -- code.7z
Aggarwal -- Flask Framework Cookbook -- 2014 -- code.7z
Web Development with Django Cookbook - Second Edition.epub
"NGINX Cookbook 高性能负载平衡高级配方" NGINX Cookbook 是一本专门介绍 NGINX 高性能负载平衡的书籍,书中涵盖了 NGINX 的高级配方和使用技巧,可以帮助读者快速搭建高性能的负载平衡系统。 GeoIP 模块和数据库...