2010-10-05 66 views
0

我试图从数组中构建散列。基本上我想获取数组的唯一字符串值并使用键构建散列。我还试图弄清楚如何记录这个独特词汇发生的次数。如何从数组中生成散列

#The text from the .txt file: 

    # **Bob and George are great! George and Sam are great. 
    #Bob, George, and sam are great!** 

    #The source code: 
    count_my_rows = File.readlines("bob.txt") 
    row_text = count_my_rows.join 

    puts row_text.split.uniq #testing to make sure array is getting filled 

反正我已经试过http://ruby-doc.org/core/classes/Hash.html

我想我需要声明一个空的哈希值与name.new开始我不知道怎么虽然它填平。我假设通过数组的迭代填充散列。我开始认为我需要将该值记录为一个单独的数组,存储它发生的时间和单词,然后将散列键指定给它。
示例= {[“Bob”,2] => 1,[“George”,3],> = 2}
留下一些代码,以便我可以仔细研究。

回答

1

为了让您一开始,

h={} 
h.default=0 
File.read("myfile").split.each do |x| 
    h[x]+=1 
end 
p h 

注:这不是完整的解决方案