Prefer using hash each_key and each_value

이 페이지는 아직 한국어로 제공되지 않으며 번역 작업 중입니다. 번역에 관한 질문이나 의견이 있으시면 언제든지 저희에게 연락해 주십시오.

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 method
hash.keys.each { |k| p k }
hash.keys.each do |k| p k end

hash.values.each { |v| p v }
hash.values.each do |v| p v end

# Updates the method and parameters
hash.each { |k, _v| p k }
hash.each do |k, _v| p k end

hash.each { |_k, v| p v }
hash.each do |_k, v| p v end

Compliant Code Examples

hash.each_key { |k| p k }
hash.each_value { |v| p v }
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis

PREVIEWING: rtrieu/product-analytics-ui-changes