-2

编写一个方法,给定一个数组,返回一个哈希,其键是数组中的单词,其值是每个单词出现的次数。

arr=["A", "man", "a", "plan", "a", "canal","Panama"]
# => {'a' => 3, 'man' => 1, 'canal' => 1, 'panama' => 1, 'plan' => 1}

我该如何做到这一点?这是我的代码:

hash={}
arr.each do |i|
    hash.each do |c,v|
       hash[c]=v+1
    end
end       
4

3 回答 3

3
hash = arr.inject({}) do |hash, element| 
  element.downcase!
  hash[element] ||= 0
  hash[element] += 1
  hash
end
于 2012-10-20T07:23:23.720 回答
3
arr.inject­(Hash.new(­0)){|h,k| k.dow­ncase!; h[k] += 1; h}
于 2012-10-20T07:24:45.950 回答
0
arr = ["A", "man", "a", "plan", "a", "canal","Panama"]
r = {}
arr.each { |e| e.downcase!; r[e] = arr.count(e) if r[e].nil? }

输出

p r
#==> {"a"=>3, "man"=>1, "plan"=>1, "canal"=>1, "panama"=>1}
于 2012-10-20T15:56:11.233 回答