简体   繁体   中英

Exclude number from SecureRandom random number generation

Let's say we have a random number generator using this:

SecureRandom.random_number(10)

Which gives you a random number from 0 to 10.

Would it be possible to exclude the number from it? Let's say it would be 8.

I was thinking about something about this:

[SecureRandom.random_number(10)].grep_v(8)

But might be there is a more correct and optimized way?

Ruby 2.7.2

Rails 6.1.2

Instead of generating a number up to 10, you could generate a number up to 9 and if the result is 8 or above, add 1:

number = SecureRandom.random_number(9)
number += 1 if number >= 8

Or you could generate a list of valid numbers and pick one of them randomly, eg via sample :

VALID_NUMBERS = [0, 1, 2, 3, 4, 5, 6, 7, 9]

number = VALID_NUMBERS.sample(random: SecureRandom)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM