2011-11-21 37 views
3

我想知道計數變量有什麼作用,最後一個結束之前?計數有什麼用途?第7行

# Pick axe page 51, chapter 4 

# Count frequency method 
def count_frequency(word_list) 
    counts = Hash.new(0) 
    for word in word_list 
     counts[word] += 1 
    end 
    counts #what does this variable actually do? 
end 

puts count_frequency(["sparky", "the", "cat", "sat", "on", "the", "mat"]) 

回答

8

任何Ruby方法的最後一個表達式是該方法的返回值。如果counts不在該方法的末尾,返回值將是for循環的結果;在這種情況下,這就是word_list陣列本身:

irb(main):001:0> def count(words) 
irb(main):002:1> counts = Hash.new(0) 
irb(main):003:1> for word in words 
irb(main):004:2>  counts[word] += 1 
irb(main):005:2> end 
irb(main):006:1> end 
#=> nil 
irb(main):007:0> count %w[ sparky the cat sat on the mat ] 
#=> ["sparky", "the", "cat", "sat", "on", "the", "mat"] 

另一種方式有人可能會寫同樣的方法在1.9:

def count_frequency(word_list) 
    Hash.new(0).tap do |counts| 
    word_list.each{ |word| counts[word]+=1 } 
    end 
end 

雖然有些人認爲使用tap這樣是濫用。 :)

而且,爲了好玩,這裏是一個稍微慢的,但是,純粹的功能版本:

def count_frequency(word_list) 
    Hash[ word_list.group_by(&:to_s).map{ |word,array| [word,array.length] } ] 
end 
+0

+1用於解釋爲什麼在該方法結束時需要「計數」行。 – Teddy

+0

所以它類似於「返回計數」,對吧?如果是這樣,對於初學者來說這很棘手,但很好知道。 – jimmyc3po

+0

@ jimmyc3po正確;在Ruby中,你可以在你的方法的任何地方放置一個顯式的'return'。然而,這並不常見。相反,最後一個表達式的結果通常用作返回值。 – Phrogz

0

重要的是一本字典,即是按鍵值的關聯圖。

在這種情況下,單詞是鍵,值是出現次數。

字典從功能count_frequency

1

它提供了該函數的返回值返回;它是如何將結果(存儲在該變量中)傳回給調用者(即,最後的代碼行)。將在Ruby函數中計算出的最後一個表達式用作返回值。

4

Ruby不要求您使用return語句在方法中返回值。如果省略明確的return語句,則將返回方法中評估的最後一行。