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

后端开发   发布日期:2025年06月21日   浏览次数:107
  1. 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

  1. "word: The"
  2. 46999283958220 这里是关键。每次都是引用同一个数组。
  3. ["The"]
  4. "word: rain"
  5. 46999283958220
  6. ["The", "rain"]
  7. "word: in"
  8. 46999283958220
  9. ["The", "rain", "in"]
  10. "word: Spain"
  11. 46999283958220
  12. ["The", "rain", "in", "Spain"]
  13. "word: falls"
  14. 46999283958220
  15. ["The", "rain", "in", "Spain", "falls"]
  16. "word: mainly"
  17. 46999283958220
  18. ["The", "rain", "in", "Spain", "falls", "mainly"]
  19. "word: in"
  20. 46999283958220
  21. ["The", "rain", "in", "Spain", "falls", "mainly", "in"]
  22. "word: the"
  23. 46999283958220
  24. ["The", "rain", "in", "Spain", "falls", "mainly", "in", "the"]
  25. "word: plain"
  26. 46999283958220
  27. ["The", "rain", "in", "Spain", "falls", "mainly", "in", "the", "plain"]
  28. {}

 



  1. 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
  1. "word: The"
  2. 46999283949940
  3. ["The"]
  4. "word: rain"
  5. 46999283924940 这里按照key取,不同的key对应不同的数组
  6. ["rain"]
  7. "word: in"
  8. ["in"]
  9. "word: Spain"
  10. 46999283923920
  11. ["Spain"]
  12. "word: falls"
  13. 46999283923420
  14. ["falls"]
  15. "word: mainly"
  16. 46999283922920
  17. ["mainly"]
  18. "word: in"
  19. ["in", "in"]
  20. "word: the"
  21. 46999283949940
  22. ["The", "the"]
  23. "word: plain"
  24. 46999283921440
  25. ["plain"]
  26. {"t"=>["The", "the"], "r"=>["rain"], "i"=>["in", "in"], "s"=>["Spain"], "f"=>["falls"], "m"=>["mainly"], "p"=>["plain"]}

 



以上就是ruby的hash学习笔记例: 将字符串文本中的单词存放在map中的详细内容,更多关于ruby的hash学习笔记例: 将字符串文本中的单词存放在map中的资料请关注九品源码其它相关文章!