为什么我的instance_variable为零? (2行代码)
我正在尝试创建一个散列,它存储不存在的键的自动递增数字。 我知道还有其他不那么脆弱的方法可以做到这一点;我的问题是:为什么我的实例变量失败得如此惨烈?
h = Hash.new{|h,k| h[k] = (@max_value += 1)}
h.instance_variable_set(:@max_value, 0) # zero ! Not nil! Argh...
puts h[:a] # expecting 1; getting NoMethodError undefined method '+' for nil:NilClass
puts h[:b] # expecting 2
puts h[:a] # expecting 1
I'm trying to create a hash which stores an auto-increment number for a non-existent key.
I'm aware there are other, less brittle, ways to do this; my question is : why does my instance variable fail so miserably?
h = Hash.new{|h,k| h[k] = (@max_value += 1)}
h.instance_variable_set(:@max_value, 0) # zero ! Not nil! Argh...
puts h[:a] # expecting 1; getting NoMethodError undefined method '+' for nil:NilClass
puts h[:b] # expecting 2
puts h[:a] # expecting 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你没有做你认为你正在做的事情。
当您调用 Hash.new 时,您正在引用 @max_value 因为它现在存在于当前范围中。当前范围是顶层,它没有在那里定义,所以你得到 nil。
然后,您在恰好也称为 @max_value 的实例上设置一个实例变量,但这不是同一件事。
你可能想要这样的东西......好吧,实际上,我无法想象这种机制是解决任何问题的良好解决方案的情况,但这正是你所要求的,所以让我们运行它。
请注意,在所有情况下,我都显式获取/设置与“h”关联的实例变量。更详细,但你需要什么。
You're not doing what you think you're doing.
When you call Hash.new, you're referencing @max_value as it exists right now in the current scope. The current scope is the top level, it's not defined there, so you get nil.
You then set an instance variable on the instance that happens to be called @max_value as well, but it's not the same thing.
You probably want something like...well, actually, I can't imagine a situation where this mechanism is a good solution to anything, but it's what you asked for so lets run with it.
Note that I'm explicitly getting/setting the instance variable associated with `h in all cases. More verbose, but what you need.