2016-11-04 163 views
2

我有我的代碼:紅寶石,運行命令行

class String 
    def freq 
    str = String "a string!" 
    self.upcase.each_char { |c| puts c + "!" } 
    str = text.split(" ") 
    wordFrequencies = Hash.new(0) 
    str.each { |str| wordFrequencies[str] += 1 } 
    wordFrequencies = wordFrequencies.sort_by {|a, b| b } 
    wordFrequencies.reverse! 
    wordFrequencies.each { |str, wordFrequencies | puts str + " " + wordFrequencies.to_s } 
    end 
end 

當我去命令行運行它,我做的:

ruby filename.rb 

,然後什麼也沒有發生 - 任何人都可以解釋爲什麼..?

+1

你寫了很多行之後才意識到它沒有做任何事情? – Stefan

回答

2

沒有任何反應,因爲你在文件中什麼都不做。

有你會想一些輸出增加

String.new.freq 

爲文件的最後一行。

或者,你可以最後end前添加以下行:

new.freq # create an instance of the class and call `freq` method on it 

這兩個選項將導致freq方法是居然叫和產生輸出。