Ruby - 哈希不存储密钥

发布于 2024-11-02 02:35:34 字数 453 浏览 0 评论 0原文

我已在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苏璃陌 2024-11-09 02:35:34

问题

通过调用

map["a"].push("hello")

您可以更改哈希的默认对象。事实上,此后,每个可能的键都会传递“hello”,但该键并未真正初始化。哈希只会知道其默认对象,但您没有告诉它“初始化”密钥。

ruby-1.9.2-head :002 > map["a"].push("Hello")
 => ["Hello"] 
ruby-1.9.2-head :003 > map["a"]
 => ["Hello"] 
ruby-1.9.2-head :004 > map["b"]
 => ["Hello"] 
ruby-1.9.2-head :004 > map.keys
 => [] 

您可能想要做的是专门初始化密钥:

ruby-1.9.2-head :008 > map["a"] = Array.new
 => [] 
ruby-1.9.2-head :009 > map.keys
 => ["a"]

但这并不是您真正想要的。

解决方案:

这种默认行为可以通过使用以下方法来初始化哈希来实现:

map = Hash.new { |hash, key| hash[key] = Array.new }

例如:(

ruby-1.9.2-head :010 > map = Hash.new { |hash, key| hash[key] = Array.new }
 => {} 
ruby-1.9.2-head :011 > map["a"]
 => [] 
ruby-1.9.2-head :012 > map["b"]
 => [] 
ruby-1.9.2-head :013 > map.keys
 => ["a", "b"] 

我不是Ruby专家,所以如果有一些建议请添加评论)

The Problem

By calling

map["a"].push("hello")

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.

ruby-1.9.2-head :002 > map["a"].push("Hello")
 => ["Hello"] 
ruby-1.9.2-head :003 > map["a"]
 => ["Hello"] 
ruby-1.9.2-head :004 > map["b"]
 => ["Hello"] 
ruby-1.9.2-head :004 > map.keys
 => [] 

What you might want to do is specifically initialize the key:

ruby-1.9.2-head :008 > map["a"] = Array.new
 => [] 
ruby-1.9.2-head :009 > map.keys
 => ["a"]

But this isn't really what you want.

Solution:

This default behavior can be achieved by using the following method to initialize the hash:

map = Hash.new { |hash, key| hash[key] = Array.new }

For example:

ruby-1.9.2-head :010 > map = Hash.new { |hash, key| hash[key] = Array.new }
 => {} 
ruby-1.9.2-head :011 > map["a"]
 => [] 
ruby-1.9.2-head :012 > map["b"]
 => [] 
ruby-1.9.2-head :013 > map.keys
 => ["a", "b"] 

(I'm no Ruby expert, so if there are some suggestions please add a comment)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文