为什么我使用注入重构的 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)
如果我理解正确的话,它不喜欢配置文件对象上的数组引用运算符我的重构版本,这意味着传递给注入的初始化程序不起作用。这种理解正确吗?如果是这样,为什么不呢?
谢谢!
I tried to do some refactoring to convert an each block into an inject, but it didn't work and I don't understand why.
Here's the code that works before refactoring:
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
and here's my refactor that doesn't work:
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
When I try and execute the refactored method I'm getting
`block in profile': undefined method `[]=' for 1:Fixnum (NoMethodError)
If I understand that correctly, it's doesn't like the array reference operator on the profile object in my refactored version, which implies that the initialiser passed to inject isn't working. Is that understanding correct? And if so, why not?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
[]=
方法返回分配的值,因此下一次迭代中profile
的值将为 1(因为它是上一次迭代的值)。为了获得您想要的行为,您必须执行以下操作:或
The
[]=
method returns the assigned value, so the value ofprofile
in the next iteration will be 1 (since it's the value of the last iteration). In order to get the behavior you want, you'll have to do:or