编写一个方法,给定一个数组,返回一个哈希,其键是数组中的单词,其值是每个单词出现的次数。
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
答案 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.downcase!; 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}