def my_string(str)
str.downcase.scan(/[[:alpha:]]+/).each_with_object(Hash.new(0)) { |s,h| h[s] += 1 }
end
str = "A cat, a dog and another cat."
my_string str
#=> {"a"=>2, "cat"=>2, "dog"=>1, "and"=>1, "another"=>1}
這使用類方法Hash::new接受一個參數爲默認值的形式。這僅僅意味着如果散列h = Hash.new(d)
沒有密鑰k
,則h[k]
返回默認值d
,這裏是0
。 (散列不變)
步驟如下。通過枚舉生成
s = str.downcase
#=> "a cat, a dog and another cat."
a = s.scan(/[[:alpha:]]+/)
#=> ["a", "cat", "a", "dog", "and", "another", "cat"]
e = a.each_with_object(Hash.new(0))
#=> #<Enumerator: ["a", "cat", "a", "dog", "and", "another", "cat"]:
# each_with_object({})>
的第一個值,並傳遞給塊,並且塊變量s
和h
被分配的值。
s,h = e.next
#=> ["a", {}]
s #=> "a"
h #=> {}
h[s] += 1
# h["a"] = h["a"] + 1 => h["a"] = 0 + 1 => h["a"] = 1
當紅寶石看到h["a"] += 1
(在解析時),她做的第一件事就是展開對h["a"] = h["a"] + 1
。由於h
最初爲空(因此沒有密鑰"a"
),所以在等號右側的h["a"]
返回默認值0
。繼續,
s,h = e.next
#=> ["cat", {"a"=>1}]
s #=> "cat"
h #=> {"a"=>1}
h[s] += 1
# h["cat"] = h["cat"] + 1 => h["cat"] = 0 + 1 => h["cat"] = 1
s,h = e.next
#=> ["a", {"a"=>1, "cat"=>1}]
s #=> "a"
h #=> {"a"=>1, "cat"=>1}
h[s] += 1
# h["a"] = h["a"] + 1 => h["a"] = 1 + 1 => h["a"] = 2
h #=> {"a"=>2, "cat"=>1}
這次h
有一個關鍵"a"
,在平等的右側,所以h["a"]
返回該鍵,1
值。
其餘的步驟是相似的。
你爲此編寫的代碼在哪裏?你的代碼的輸出是什麼?什麼不準確地工作? – Surya
到目前爲止,我還沒有真正走得很遠。如果有辦法做到這一點,我試圖看到任何新人。 – Joseph
另一種方式來做這個'string.split.group_by(&:本身).transform_values(&:size)' –