---
title: "在 Ruby 中自动创建中间层的 Hashtable"
description: "所有中间层的 hashtable 都会魔法般地自动创建出来"
canonical: https://oozou.com/til/automagical-intermediate-level-hashtables-in-ruby-62
locale: zh-Hans
date: 2020-10-13
topic: ruby
---

# 在 Ruby 中自动创建中间层的 Hashtable

> 所有中间层的 hashtable 都会魔法般地自动创建出来

Published: 2020-10-13 · Topic: [ruby](https://oozou.com/zh-Hans/til-topics/ruby) ([markdown](https://oozou.com/zh-Hans/til-topics/ruby.md))

所有中间层的 hashtable 都会魔法般地自动创建出来

```ruby
def autovivifying_hash
   Hash.new {|ht,k| ht[k] = autovivifying_hash}
end
```

### 用法

```ruby
response_builder = autovivifying_hash
response_builder['payment']['status'] = 'OK'
response_builder # => {"payment"=>{"status"=>"OK"}
```

---

Contact OOZOU: hello@oozou.com · +66 2544 0000 · https://oozou.com/zh-Hans/contact

More for AI agents: https://oozou.com/llms.txt · every page has a markdown twin at its URL plus ".md"
