【问题标题】:Why isn't this Ruby hash what I thought it would be?为什么这个 Ruby 哈希不是我想象的那样?
【发布时间】:2012-12-25 01:06:36
【问题描述】:

我有这个代码:

$ze = Hash.new( Hash.new(2) )

$ze['test'] = {0=> 'a', 1=>'b', 3 => 'c'}

$ze[5][0] = 'one'
$ze[5][1] = "two"

puts $ze
puts $ze[5]

这是输出:

{"test"=>{0=>"a", 1=>"b", 3=>"c"}} 
{0=>"one", 1=>"two"}

为什么没有输出:

{"test"=>{0=>"a", 1=>"b", 3=>"c"}, 5=>{0=>"one", 1=>"two"}} 
{0=>"one", 1=>"two"}

【问题讨论】:

  • 不要使用全局变量,它们很丑!

标签: ruby hashmap


【解决方案1】:

使用$ze[5][0] = xxx,您首先调用$ze 的getter [],然后调用$ze[5] 的setter []=。见Hash's API

如果$ze 不包含键,它将返回您使用Hash.new(2) 初始化的默认值。

$ze[5][0] = 'one'
# in detail
$ze[5] # this key does not exist,
       # this will then return you default hash.
default_hash[0] = 'one'

$ze[5][1] = 'two'
# the same here
default_hash[1] = 'two'

您没有向$ze 添加任何内容,而是向其默认哈希添加键/值对。 这就是为什么你也可以这样做。你会得到和$ze[5]一样的结果。

puts $ze[:do_not_exist]
# => {0=>"one", 1=>"two"}

【讨论】:

  • 哦!我没有意识到你甚至可以修改默认哈希。谢谢。
【解决方案2】:
h = Hash.new(2)
print "h['a'] : "; p h['a']

$ze = Hash.new( Hash.new(2) )
print '$ze[:do_not_exist]    : '; p $ze[:do_not_exist]
print '$ze[:do_not_exist][5] : '; p $ze[:do_not_exist][5]

$ze = Hash.new{|hash, key| hash[key] = {}}
$ze['test'] = {0=> 'a', 1=>'b', 3 => 'c'}
$ze[5][0] = 'one'
$ze[5][1] = "two"
print '$ze : '; p $ze

执行:

$ ruby -w t.rb
h['a'] : 2
$ze[:do_not_exist]    : {}
$ze[:do_not_exist][5] : 2
$ze : {"test"=>{0=>"a", 1=>"b", 3=>"c"}, 5=>{0=>"one", 1=>"two"}}

【讨论】:

    猜你喜欢
    • 2016-10-23
    • 1970-01-01
    • 2021-09-10
    • 2013-04-08
    • 2019-10-18
    • 1970-01-01
    • 2011-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多