swap.nil - 10 months ago 87

Ruby Question

Trying to generate random digits with SecureRandom class of rails. Can we create a random number with SecureRandom.hex which includes only digits and no alphabets.

For example:

Instead of

`SecureRandom.hex(4)`

=> "95bf7267"

It should give

`SecureRandom.hex(4)`

=> "95237267"

Answer

Check out the api for SecureRandom: http://rails.rubyonrails.org/classes/ActiveSupport/SecureRandom.html

I believe you're looking for a different method: #random_number.

```
SecureRandom.random_number(a_big_number)
```

Since #hex returns a hexadecimal number, it would be unusual to ask for a random result that contained only numerical characters.

For basic use cases, it's simple enough to use #rand.

```
rand(9999)
```

Edited:

I'm not aware of a library that generates a random number of specified length, but it seems simple enough to write one. Here's my pass at it:

```
def rand_by_length(length)
rand((9.to_s * length).to_i).to_s.center(length, rand(9).to_s).to_i
end
```

The method #rand_by_length takes an integer specifying length as a param and tries to generate a random number of max digits based on the length. String#center is used to pad the missing numbers with random number characters. Worst case calls #rand for each digit of specified length. That may serve your need.