The “Avoid Random” rule is focused on discouraging the use of the rand method with negative numbers or without any arguments. This is because rand without arguments returns a floating-point number between 0 and 1, which can lead to unpredictable results and make the code harder to test and debug. Moreover, using rand with negative numbers is not allowed and will raise an error.
This rule is important because it promotes the use of predictable and testable code. Randomness in code can lead to inconsistent behavior, which makes it more difficult to identify and fix bugs. Additionally, the use of a random number generator without a defined range or with a negative range can lead to unexpected results or runtime errors, respectively.
To avoid this, always use rand with a positive integer argument to define the range of the random numbers that can be generated. This ensures that the output is predictable and within a specific range. For example, use rand(100) to generate a random number between 0 and 99. If you need a random floating-point number within a specific range, you can use rand in combination with Range#to_a, like rand(1.0..10.0). This will generate a random floating-point number between 1.0 and 10.0.
Non-Compliant Code Examples
rand(-100)
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-security # Rules to enforce Ruby security.
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