博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ruby的hash学习笔记例: 将字符串文本中的单词存放在map中
阅读量:4310 次
发布时间:2019-06-06

本文共 1592 字,大约阅读时间需要 5 分钟。

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"]}

 

 

转载于:https://www.cnblogs.com/or2-/p/5011405.html

你可能感兴趣的文章
sql server从一个数据库复制一个表到另一个数据库的方法
查看>>
微软正式公布Win8版本 ARM版命名为Windows RT
查看>>
4.java设计模式-原型模式(prototype)
查看>>
Javaee -----01----javaee的环境搭建和html标签 ...
查看>>
JVM内存分布和垃圾回收
查看>>
DOM操作指令
查看>>
PHPCMS快速建站系列之类别调用及类别显示页面
查看>>
《第二章 感知机》
查看>>
HomeWork1_Login in
查看>>
javascript中的类
查看>>
新词发现博文收集
查看>>
input text focus去掉默认光影
查看>>
使用JsonP进行跨域请求
查看>>
HDU 5317 RGCDQ (数论素筛)
查看>>
学习JSP(一)
查看>>
node安装-Win+Linux+Mac osx
查看>>
cookie和session笔记
查看>>
Java中使用注释
查看>>
构建你的第一个App
查看>>
Network Mapper 嗅探工具
查看>>