2015-12-22 105 views
2

我在做這個練習的Ruby紅寶石鍛鍊:關於哈希

寫一個函數,letter_count(str)接受一個string和 返回一個散列映射每個字母其頻率。不包括 空格。

這是一個解決方案:

def letter_count(str) 
    counts = Hash.new(0) 
    str.each_char do |char| 
    counts[char] += 1 unless char == " " 
    end 
    counts 
end 

是什麼counts[char] += 1意思? char == " "是什麼意思?

+0

[+ =](https://www.google.com/search?q=ruby+plus+equals) – abl

+0

'counts'是一個散列,因此'counts [char]'是散列的值該鍵等於局部變量'char'的值。例如,'count [「a」]'是鍵'「a」'的值。 '「a」'是一個字符串(即使它由單個字符組成)。 Ruby沒有字符對象。 Ruby將'count [char] + = 1'擴展爲'counts [char] = counts [char] + 1',然後執行它。 'count [char] ==「」'如果'char'是由單個空格字符組成的字符串,則返回true。 'Hash.new(0)'是問題的關鍵。你需要明白這一點。 –

+0

非常好的解釋,我想我錯過了Hash.new(0)中的重要0,並且非常感謝你Cary –

回答

2

在紅寶石,+= desugars到=+。所以counts[char] += 1變成counts[char] = counts[char] + 1。現在,通常,如果密鑰不存在於散列中,則散列訪問方法[]將返回nil,這就是爲什麼我們將0傳遞給構造函數的原因。如果某個鍵不存在,則將值傳遞給構造函數使得「默認」返回值。所以,如果counts[char]存在,它增加了一個給它,如果它不,它初始化爲0 + 1,這僅僅是1

至於在最後的比較,unless char == " "爲後綴的條件,一個是Perlism遷移到Ruby。在Ruby中,你可以在行尾寫入條件,所以以下三者是等價的。

# One 
if not foo 
    bar 
end 
# Two 
bar if not foo 
# Three 
bar unless foo 

問題描述說,排除空格,因此unless char == " "確保在哈希增量操作將運行,除非該字符是一個空格。

+1

Ruby的任何新手都不太可能理解「desugars」的含義。 –

+0

非常感謝Silvio,這已經清理了很多。我想我會更好地理解,如果我睡着了。 –

3

世界上有什麼計數[char] + = 1 mean?

+=是 「通過增量和分配」,即簡寫本可以寫成:

count = counts[char] # retrieve the value at index "char" 
count = count + 1 # add one 
counts[char] = count # set the value at index "char" to the new value 

而且什麼呢焦炭== 「」 是什麼意思?

==是等號運算符。 a == b返回true如果ab具有相同的值。所以如果char是空格字符,則char == " "返回true。在這種情況下,相等性測試的結果是倒數unless,所以它最終意味着「除了字符是空格之外,爲這個字符加1」。

+0

謝謝,我錯過了引號之間的空格:D –

1

什麼在世界上計數[字符] + = 1的意思是?

a += 1a = a + 1是等同的。此外,使用counts = Hash.new(0)時,0將被設置爲新密鑰的值(如果該密鑰未退出)。所以,如果char是新的,counts[char]變成1counts[char] += 1。如果是第二次看到char,counts[char]由於1已被設置爲counts[char]而變爲2counts[char] += 1

Alsowhat does char ==「」是什麼意思?

char == " "如果char是「」(空格字符)則返回true。

+0

謝謝Masashi,我認爲在Hash.new(0)處的0是我遺漏並困惑了我。 –