---
title: Avoid Random
description: Datadog, the leading service for cloud-scale monitoring.
breadcrumbs: >-
  Docs > Datadog Security > Code Security > Static Code Analysis (SAST) > SAST
  Rules > Avoid Random
---

# Avoid Random

{% callout %}
# Important note for users on the following Datadog sites: app.ddog-gov.com

{% alert level="danger" %}
This product is not supported for your selected [Datadog site](https://docs.datadoghq.com/getting_started/site). ().
{% /alert %}

{% /callout %}

## Metadata{% #metadata %}

**ID:** `ruby-security/avoid-random`

**Language:** Ruby

**Severity:** Notice

**Category:** Security

**CWE**: [330](https://cwe.mitre.org/data/definitions/330.html)

## Description{% #description %}

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{% #non-compliant-code-examples %}

```ruby
rand(-100)
```

## Compliant Code Examples{% #compliant-code-examples %}

```ruby
SecureRandom.rand(0...2.0)
Faker::Number.rand(10..100)
```
  Seamless integrations. Try Datadog Code SecurityDatadog Code Security 
{% icon name="icon-external-link" /%}
 