Ruby - 哈希不存储密钥
我已在 irb 中执行了以下操作:
irb(main):068:0* map = Hash.new(Array.new)
=> {}
irb(main):069:0> map["a"]
=> []
irb(main):070:0> map["a"].push("hello")
=> ["hello"]
irb(main):071:0> map["a"].push(1)
=> ["hello", 1]
irb(main):072:0> map.has_key?("a")
=> false
irb(main):073:0> map.keys
=> []
irb(main):074:0>
为什么一旦我将密钥 "a"
添加到哈希中,它就没有出现在 Hash#keys
的结果中?
谢谢
I have executed the following in irb:
irb(main):068:0* map = Hash.new(Array.new)
=> {}
irb(main):069:0> map["a"]
=> []
irb(main):070:0> map["a"].push("hello")
=> ["hello"]
irb(main):071:0> map["a"].push(1)
=> ["hello", 1]
irb(main):072:0> map.has_key?("a")
=> false
irb(main):073:0> map.keys
=> []
irb(main):074:0>
Why is it that once i have added key "a"
to the hash it is not appearing in the result of Hash#keys
?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题
通过调用
您可以更改哈希的默认对象。事实上,此后,每个可能的键都会传递“hello”,但该键并未真正初始化。哈希只会知道其默认对象,但您没有告诉它“初始化”密钥。
您可能想要做的是专门初始化密钥:
但这并不是您真正想要的。
解决方案:
这种默认行为可以通过使用以下方法来初始化哈希来实现:
例如:(
我不是Ruby专家,所以如果有一些建议请添加评论)
The Problem
By calling
you alter the Hash's default object. In fact, after that, every possible key will deliver "hello", but the key isn't really initialized. The hash will only know its default object, but you didn't tell it to "initialize" the key.
What you might want to do is specifically initialize the key:
But this isn't really what you want.
Solution:
This default behavior can be achieved by using the following method to initialize the hash:
For example:
(I'm no Ruby expert, so if there are some suggestions please add a comment)