- 필수 기능
- 시작하기
- Glossary
- 표준 속성
- Guides
- Agent
- 통합
- 개방형텔레메트리
- 개발자
- API
- Datadog Mobile App
- CoScreen
- Cloudcraft
- 앱 내
- 서비스 관리
- 인프라스트럭처
- 애플리케이션 성능
- APM
- Continuous Profiler
- 스팬 시각화
- 데이터 스트림 모니터링
- 데이터 작업 모니터링
- 디지털 경험
- 소프트웨어 제공
- 보안
- AI Observability
- 로그 관리
- 관리
ID: ruby-best-practices/hash-fetch
Language: Ruby
Severity: Notice
Category: Best Practices
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.
test = { foo: 'foo', bar: 'bar', magic_num: 42 }
test[:foo] # => 'foo'
test[:qux] # => nil
def foo(opts)
puts opts[:bar]
end
test = { foo: 'foo', bar: 'bar' }
test.fetch(:foo) # => 'foo'
test[:bar] = 42
test.fetch(:qux) # => KeyError
|
|
For more information, please read the Code Analysis documentation
Identify code vulnerabilities directly in yourVS Code editor
Identify code vulnerabilities directly inJetBrains products