2010-09-27 66 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

相关问题