The rule “Wrap assignment in condition” is designed to avoid a common programming bug where a single equals sign (=) is used in a conditional statement instead of a double equals sign (==). This can lead to unexpected behavior because the single equals sign is used for assignment in Ruby, not for comparison.
This is important because using assignment in a conditional statement can lead to code that is hard to read and understand. It can also lead to bugs if the assignment is unintentional. The assignment will always return a truthy value unless the assigned value is nil or false, which may not be the expected behavior.
To avoid violating this rule, always use double equals (==) for comparison in conditional statements. If you need to assign a value and use it in the condition, you should do the assignment outside of the conditional statement. If you must do the assignment inside the condition, wrap the assignment in parentheses to make it clear that the assignment is intentional. This improves code readability and helps prevent bugs.
Non-Compliant Code Examples
ifv=array.grep(/foo/)do_something(v)# some codeend
Compliant Code Examples
if(v=array.grep(/foo/))do_something(v)# some codeendv=array.grep(/foo/)ifvdo_something(v)# some codeend
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