• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ruby的hash学习笔记例:将字符串文本中的单词存放在map中

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
text = 'The rain in Spain falls mainly in the plain.'
first = Hash.new []
second = Hash.new {|hash,key| hash[key] = []}


text.split(/\W+/).each do |word|
p "word: #{word}"
p first[word[0, 1].downcase].object_id
first[word[0, 1].downcase] << word
p first[word[0, 1].downcase]
end
p first

"word: The"
46999283958220  这里是关键。每次都是引用同一个数组。
["The"]
"word: rain"
46999283958220
["The", "rain"]
"word: in"
46999283958220
["The", "rain", "in"]
"word: Spain"
46999283958220
["The", "rain", "in", "Spain"]
"word: falls"
46999283958220
["The", "rain", "in", "Spain", "falls"]
"word: mainly"
46999283958220
["The", "rain", "in", "Spain", "falls", "mainly"]
"word: in"
46999283958220
["The", "rain", "in", "Spain", "falls", "mainly", "in"]
"word: the"
46999283958220
["The", "rain", "in", "Spain", "falls", "mainly", "in", "the"]
"word: plain"
46999283958220
["The", "rain", "in", "Spain", "falls", "mainly", "in", "the", "plain"]
{}

 



text.split(/\W+/).each do |word|
p "word: #{word}"
p second[word[0, 1].downcase].object_id
second[word[0, 1].downcase] << word
p second[word[0, 1].downcase]
end
p second
"word: The"
46999283949940
["The"]
"word: rain"
46999283924940  这里按照key取,不同的key对应不同的数组
["rain"]
"word: in"
46999283924440
["in"]
"word: Spain"
46999283923920
["Spain"]
"word: falls"
46999283923420
["falls"]
"word: mainly"
46999283922920
["mainly"]
"word: in"
46999283924440
["in", "in"]
"word: the"
46999283949940
["The", "the"]
"word: plain"
46999283921440
["plain"]
{"t"=>["The", "the"], "r"=>["rain"], "i"=>["in", "in"], "s"=>["Spain"], "f"=>["falls"], "m"=>["mainly"], "p"=>["plain"]}

 




鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Web自动化测试框架Watir(基于Ruby) - 第2章 使用Watir写自动化测试脚本 ...发布时间:2022-07-14
下一篇:
【Ruby】删除旧文件发布时间:2022-07-14
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap