---
title: "在 Ruby 中自動建立中間層的 Hashtable"
description: "所有中間層的 hashtable 都會自動神奇地建立起來"
canonical: https://oozou.com/til/automagical-intermediate-level-hashtables-in-ruby-62
locale: zh-Hant
date: 2020-10-13
topic: ruby
---

# 在 Ruby 中自動建立中間層的 Hashtable

> 所有中間層的 hashtable 都會自動神奇地建立起來

Published: 2020-10-13 · Topic: [ruby](https://oozou.com/zh-Hant/til-topics/ruby) ([markdown](https://oozou.com/zh-Hant/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-Hant/contact

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