diff options
| author | Yukihiro "Matz" Matsumoto <[email protected]> | 2014-04-27 03:03:27 +0900 |
|---|---|---|
| committer | Yukihiro "Matz" Matsumoto <[email protected]> | 2014-04-27 03:03:27 +0900 |
| commit | 7e175d8130bf329d44368a057587a9e4b3133589 (patch) | |
| tree | 05bcc28852e18a4369b8fdaa45368bcad7227a29 /mrbgems/mruby-hash-ext/mrblib/hash.rb | |
| parent | 855a3f599188ef0e3c86f95410317d7f212e6ceb (diff) | |
| download | mruby-7e175d8130bf329d44368a057587a9e4b3133589.tar.gz mruby-7e175d8130bf329d44368a057587a9e4b3133589.zip | |
add Hash#fetch; close #2134
Diffstat (limited to 'mrbgems/mruby-hash-ext/mrblib/hash.rb')
| -rw-r--r-- | mrbgems/mruby-hash-ext/mrblib/hash.rb | 14 |
1 files changed, 14 insertions, 0 deletions
diff --git a/mrbgems/mruby-hash-ext/mrblib/hash.rb b/mrbgems/mruby-hash-ext/mrblib/hash.rb index 723a0b907..bf3836514 100644 --- a/mrbgems/mruby-hash-ext/mrblib/hash.rb +++ b/mrbgems/mruby-hash-ext/mrblib/hash.rb @@ -13,4 +13,18 @@ class Hash alias each_pair each alias update merge! + + def fetch(key, none=NONE, &block) + unless self.key?(key) + if block + block.call + elsif none != NONE + none + else + raise RuntimeError, "Key not found: #{key}" + end + else + self[key] + end + end end |
