- 필수 기능
- 시작하기
- Glossary
- 표준 속성
- Guides
- Agent
- 통합
- 개방형텔레메트리
- 개발자
- Administrator's Guide
- API
- Datadog Mobile App
- CoScreen
- Cloudcraft
- 앱 내
- 서비스 관리
- 인프라스트럭처
- 애플리케이션 성능
- APM
- Continuous Profiler
- 스팬 시각화
- 데이터 스트림 모니터링
- 데이터 작업 모니터링
- 디지털 경험
- 소프트웨어 제공
- 보안
- AI Observability
- 로그 관리
- 관리
ID: ruby-best-practices/hash-fetch-default
Language: Ruby
Severity: Notice
Category: Best Practices
This rule emphasizes the importance of using the fetch
method with a default value in Ruby, rather than a custom check. This is because the fetch
method correctly handles ‘falsey’ values, such as false
or nil
, and will return them when they are the actual value associated with a key in a hash. This prevents unexpected results that may occur when using a custom check, as it may incorrectly evaluate a ‘falsey’ value as not present and return the default value instead.
The importance of this rule lies in the accuracy and predictability of your code. It ensures that you are correctly handling all potential values in a hash and not mistakenly returning a default value when the key is present but associated with a ‘falsey’ value. This can lead to bugs that are hard to track down and fix in your code.
To abide by this rule, always use the fetch
method with a default value when checking if a key is present in a hash and you want to return a default value if it isn’t. This method will correctly handle all values, including ‘falsey’ ones, and return the accurate result. For example, instead of using hash[:key] || default_value
, use hash.fetch(:key, default_value)
.
test = { foo: 'foo', is_bar: false }
# on a falsey value, you get unexpected results
test[:is_bar] || true # => true
test = { foo: 'foo', is_bar: false }
# fetch works on falsey values, so you get expected results
test.fetch(:is_bar, true) # => false
|
|
For more information, please read the Code Analysis documentation
Identify code vulnerabilities directly in yourVS Code editor
Identify code vulnerabilities directly inJetBrains products