Use fetch to check hash keys

이 페이지는 아직 한국어로 제공되지 않으며 번역 작업 중입니다. 번역에 관한 질문이나 의견이 있으시면 언제든지 저희에게 연락해 주십시오.

Metadata

ID: ruby-best-practices/hash-fetch

Language: Ruby

Severity: Notice

Category: Best Practices

Description

The rule “Use fetch to check hash keys” encourages the use of the fetch method over the direct hash access method [] for checking hash keys. This is because fetch raises an error when the key does not exist in the hash, making the code more robust and fail-safe by preventing any unexpected behavior due to missing hash keys.

The significance of this rule lies in its ability to make the code more predictable and error-resistant. When a hash key is accessed directly using [], and the key does not exist, Ruby returns nil by default. This can lead to subtle bugs if the existence of the key is crucial for the subsequent code. Using fetch, on the other hand, will raise a KeyError if the key is not found, making it immediately clear that there’s an issue with the code.

Adhering to this rule is straightforward. Instead of using direct hash access, use the fetch method whenever you need to access a hash key. For example, instead of hash[:key], use hash.fetch(:key). This way, if the key does not exist in the hash, your code will raise an error, allowing you to catch and handle the problem early on.

Non-Compliant Code Examples

test = { foo: 'foo', bar: 'bar', magic_num: 42 }
test[:foo] # => 'foo'
test[:qux] # => nil

def foo(opts)
  puts opts[:bar]
end

Compliant Code Examples

test = { foo: 'foo', bar: 'bar' }
test.fetch(:foo) # => 'foo'
test[:bar] = 42
test.fetch(:qux) # => KeyError
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis

PREVIEWING: may/unit-testing