2017-09-29 17 views
0

如何使用將字符串作爲參數的方法,並將其轉換爲顯示鍵的散列:作爲單詞和值:作爲單詞出現在字符串中的次數?如何使用將字符串作爲參數的方法,並將其變爲散列?

def my_string(string) 

end 

my_string("This is my string, or could be any string.") 

我在想,我將不得不string.split(" "),並以某種方式使用數組。

def my_string(string) 
    string.split(" ") 

    string_hash = {} 

    string.each_with_index do |element, index| 
    string_hash[index] = element 
    end 
end 

my_string("This is my string, or could be any string.") 
+0

你爲此編寫的代碼在哪裏?你的代碼的輸出是什麼?什麼不準確地工作? – Surya

+0

到目前爲止,我還沒有真正走得很遠。如果有辦法做到這一點,我試圖看到任何新人。 – Joseph

+1

另一種方式來做這個'string.split.group_by(&:本身).transform_values(&:size)' –

回答

3
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({})> 

的第一個值,並傳遞給塊,並且塊變量sh被分配的值。

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值。

其餘的步驟是相似的。

+0

最後,一個適用於21世紀的正則表達式:) –

+1

'Enumerable#count_by'確實是一個缺失的部分。 ( –

+0

)爲什麼'split'而不是'scan',雖然?後者似乎更合適,意圖明智。 –

相關問題