Use &&= to check if a variable may exist

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

Metadata

ID: ruby-best-practices/existence-check-shorthand

Language: Ruby

Severity: Info

Category: Best Practices

Description

The &&= operator in Ruby is a conditional assignment operator that checks if a variable is truthy (not nil or false). If the variable is truthy, it assigns the value on the right side of the operator to the variable. This rule emphasizes the importance of using this operator to avoid unnecessary checks and potential errors in your code.

It is important to use &&= operator to ensure your code is efficient and clean. Using this operator can help to avoid unnecessary conditional checks and keep your code concise. More importantly, it can prevent potential nil errors which are common in Ruby when trying to call a method on a nil object.

To follow this rule, use &&= operator when you need to check if a variable may exist and assign a value to it. For example, instead of doing if foo; bar = foo.something; end, you can do bar &&= foo.something. This will assign foo.something to bar only if bar is not nil or false.

Non-Compliant Code Examples

if foo
     bar = foo.something
end

if foo
     bar = foo.something
else
     bar = foo.something_else
end

Compliant Code Examples

bar &&= foo.something

if foo
     bar = foo.something
else
     bar = foo.something_else
end
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