Skip to content

Add Hash#fetch method#275

Merged
hasumikin merged 2 commits intomrubyc:masterfrom
khasinski:feature/hash-fetch
Mar 13, 2026
Merged

Add Hash#fetch method#275
hasumikin merged 2 commits intomrubyc:masterfrom
khasinski:feature/hash-fetch

Conversation

@khasinski
Copy link
Contributor

@khasinski khasinski commented Mar 8, 2026

Summary

Adds Hash#fetch(key[, default]) method.

This is useful for reading configuration values safely. When a required key is missing and no default is given, fetch raises an error instead of returning nil silently. This helps catch mistakes early.

config = {timeout: 30, retries: 3}

config.fetch(:timeout)       #=> 30
config.fetch(:missing, 10)   #=> 10
config.fetch(:missing)       #=> raises error

Supports KeyError semantics (raises RuntimeError since KeyError is not available in mruby/c).

Changes

  • Add c_hash_fetch function in src/c_hash.c
  • Register fetch method in Hash class

Implements Hash#fetch(key[, default]) which raises an error
when a key is missing and no default is given.
@hasumikin
Copy link
Member

@khasinski
The core team will discuss the necessity of this method and decide whether to merge it, but you need to write tests for it at least.

@khasinski
Copy link
Contributor Author

@hasumikin Thank you for the review! I added tests for fetch in test/hash_test.rb.

Please take your time to discuss with the team. Happy to make any changes if needed.

@hasumikin hasumikin merged commit e51b151 into mrubyc:master Mar 13, 2026
8 checks passed
@khasinski khasinski deleted the feature/hash-fetch branch March 13, 2026 16:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants