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)
如果我理解正確,它不喜歡數組引用操作符在我的重構版本中,這意味着初始化程序通過注入不起作用。這種理解是否正確?如果是這樣,爲什麼不呢?
謝謝!
啊...... *拍打前額*在事後明顯。 +10將我介紹給Object#tap! – 2010-09-27 05:26:13