Cette page n'est pas encore disponible en français, sa traduction est en cours. Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.
Metadata
ID:ruby-best-practices/hash-each
Language: Ruby
Severity: Notice
Category: Best Practices
Description
The rule “Prefer using hash each_key and each_value” recommends using the specific iterator methods each_key and each_value when iterating over the keys or values of a hash. It is considered a best practice in Ruby to use these methods instead of the more general each method followed by keys or values.
This rule is important because it helps to improve the readability and clarity of your code. When you use each_key or each_value, it’s immediately clear that you’re working with either the keys or the values of the hash. This makes your code easier to understand and maintain.
To follow this rule, you should replace any instances of hash.keys.each with hash.each_key, and hash.values.each with hash.each_value. This will make your code more idiomatic and easier to read, while still achieving the same functionality.
Non-Compliant Code Examples
# Updates the methodhash.keys.each{|k|pk}hash.keys.eachdo|k|pkendhash.values.each{|v|pv}hash.values.eachdo|v|pvend# Updates the method and parametershash.each{|k,_v|pk}hash.eachdo|k,_v|pkendhash.each{|_k,v|pv}hash.eachdo|_k,v|pvend
Compliant Code Examples
hash.each_key{|k|pk}hash.each_value{|v|pv}
Seamless integrations. Try Datadog Code Analysis
Datadog Code Analysis
Try this rule and analyze your code with Datadog Code Analysis
How to use this rule
1
2
rulesets:- ruby-best-practices # Rules to enforce Ruby best practices.
Create a static-analysis.datadog.yml with the content above at the root of your repository
Use our free IDE Plugins or add Code Analysis scans to your CI pipelines