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}
シームレスな統合。 Datadog Code Security をお試しください
Datadog Code Security
このルールを試し、Datadog Code Security でコードを解析する
このルールの使用方法
1
2
rulesets:- ruby-best-practices # Rules to enforce Ruby best practices.