2010-09-27 42 views
3

我試圖做一些重構將每個塊轉換爲注入,但它沒有工作,我不明白爲什麼。爲什麼我的重構ruby沒有使用注入工作?

這裏的重構之前的作品代碼:

class String 
    # Build the word profile for the given word. The word profile is an array of 
    # 26 integers -- each integer is a count of the number of times each letter 
    # appears in the word. 
    # 
    def profile 
    profile = Array.new(26) { 0 } 
    self.downcase.split(//).each do |letter| 
     # only process letters a-z 
     profile[letter.ord - 'a'.ord] += 1 unless letter.ord > 'z'.ord 
    end 
    profile 
    end 
end 

,這裏是我的重構不起作用:

class String 
    # Build the word profile for the given word. The word profile is an array of 
    # 26 integers -- each integer is a count of the number of times each letter 
    # appears in the word. 
    # 
    def profile 
    self.downcase.split(//).inject(Array.new(26) {0}) do |profile, letter| 
     # only process letters a-z 
     profile[letter.ord - 'a'.ord] += 1 unless letter.ord > 'z'.ord 
    end 
    end 
end 

當我嘗試和執行重構方法我越來越

`block in profile': undefined method `[]=' for 1:Fixnum (NoMethodError) 

如果我理解正確,它不喜歡數組引用操作符在我的重構版本中,這意味着初始化程序通過注入不起作用。這種理解是否正確?如果是這樣,爲什麼不呢?

謝謝!

回答

3

[]=方法返回分配的值,所以profile在下一次迭代中的值將爲1(因爲它是最後一次迭代的值)。爲了得到你想要的行爲,你就必須做:

self.downcase.split(//).inject(Array.new(26) {0}) do |profile, letter| 
    # only process letters a-z 
    profile[letter.ord - 'a'.ord] += 1 unless letter.ord > 'z'.ord 
    profile 
end 

self.downcase.split(//).inject(Array.new(26) {0}) do |profile, letter| 
    # only process letters a-z 
    profile.tap { profile[letter.ord - 'a'.ord] += 1 unless letter.ord > 'z'.ord } 
end 
+0

啊...... *拍打前額*在事後明顯。 +10將我介紹給Object#tap! – 2010-09-27 05:26:13

相關問題