This product is not supported for your selected Datadog site. ().
이 페이지는 아직 영어로 제공되지 않습니다. 번역 작업 중입니다. 현재 번역 프로젝트에 대한 질문이나 피드백이 있으신 경우 언제든지 연락주시기 바랍니다.
Metadata
ID:ruby-best-practices/hash-fetch-default
Language: Ruby
Severity: Notice
Category: Best Practices
Description
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).
Non-Compliant Code Examples
test={foo:'foo',is_bar:false}# on a falsey value, you get unexpected resultstest[:is_bar]||true# => true
Compliant Code Examples
test={foo:'foo',is_bar:false}# fetch works on falsey values, so you get expected resultstest.fetch(:is_bar,true)# => false
원활한 통합. Datadog Code Security를 경험해 보세요
Datadog Code Security
이 규칙을 사용해 Datadog Code Security로 코드를 분석하세요
규칙 사용 방법
1
2
rulesets:- ruby-best-practices # Rules to enforce Ruby best practices.
리포지토리 루트에 위의 내용을 포함하는 static-analysis.datadog.yml을 만듭니다
무료 IDE 플러그인을 사용하거나 CI 파이프라인에 Code Security 검사를 추가합니다