- 필수 기능
- 시작하기
- Glossary
- 표준 속성
- Guides
- Agent
- 통합
- 개방형텔레메트리
- 개발자
- Administrator's Guide
- API
- Datadog Mobile App
- CoScreen
- Cloudcraft
- 앱 내
- 서비스 관리
- 인프라스트럭처
- 애플리케이션 성능
- APM
- Continuous Profiler
- 스팬 시각화
- 데이터 스트림 모니터링
- 데이터 작업 모니터링
- 디지털 경험
- 소프트웨어 제공
- 보안
- AI Observability
- 로그 관리
- 관리
ID: ruby-best-practices/array-coercion
Language: Ruby
Severity: Notice
Category: Best Practices
The rule “Use Array()
to ensure your variable is an array” is important for ensuring your code behaves as expected, regardless of the type of data it receives. It is common in Ruby to need to iterate through an array of items. However, if the variable is not an array, this can lead to unexpected behavior or errors.
The Array()
method in Ruby is a Kernel method that converts its argument to an Array. If the argument is already an Array, it returns the argument. If the argument is nil, it returns an empty Array. This can be used to ensure that a variable is an array before trying to iterate over it, preventing potential errors or unexpected behavior.
By using Array(foos)
, you can ensure that foos
is an array before you try to iterate over it with each
. This prevents the need to check if foos
is an array with foos.is_a?(Array)
and makes your code cleaner and easier to understand.
foos = [foos] unless foos.is_a?(Array)
foos.each { |path| do_bar(path) }
# this would always create a new Array instance
[*foos].each { |foo| do_bar(foo) }
Array(foos).each { |foo| do_bar(foo) }
|
|
For more information, please read the Code Analysis documentation
Identify code vulnerabilities directly in yourVS Code editor
Identify code vulnerabilities directly inJetBrains products