I tried to do some refactoring to convert each block into an injection, but it didn’t work, and I don’t understand why.
Here is the code that works before refactoring:
class String
def profile
profile = Array.new(26) { 0 }
self.downcase.split(//).each do |letter|
profile[letter.ord - 'a'.ord] += 1 unless letter.ord > 'z'.ord
end
profile
end
end
and here is my refactor that doesn't work:
class String
def profile
self.downcase.split(//).inject(Array.new(26) {0}) do |profile, letter|
profile[letter.ord - 'a'.ord] += 1 unless letter.ord > 'z'.ord
end
end
end
When I try to execute a processed method, I get
`block in profile': undefined method `[]=' for 1:Fixnum (NoMethodError)
If I understand this correctly, he does not like the array reference operator in the profile object in my refactored version, which implies that the initializer passed to the injection does not work. Is this understanding correct? And if so, why not?
Thank!
source
share