给定一个数组,返回一个哈希值

时间:2012-10-20 07:17:37

标签: ruby

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

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       

3 个答案:

答案 0 :(得分:3)

hash = arr.inject({}) do |hash, element| 
  element.downcase!
  hash[element] ||= 0
  hash[element] += 1
  hash
end

答案 1 :(得分:3)

arr.inject­(Hash.new(­0)){|h,k| k.dow­ncase!; h[k] += 1; h}

答案 2 :(得分: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}