Random Numbers in Ruby
Here’s the translation of the Go code to Ruby, formatted in Markdown suitable for Hugo:
Ruby’s Random
class provides pseudorandom number generation.
Some of the generated numbers may be different when you run the sample.
See the Random
class documentation for references on other random quantities that Ruby can provide.
In Ruby, the Random
class is used for generating random numbers. It’s part of the standard library, so no additional imports are needed beyond require 'random'
.
The Random.rand
method is versatile:
- When called without arguments, it returns a float between 0 and 1.
- When given an integer argument
n
, it returns a random integer between 0 and n-1. - When given a range, it returns a random element from that range.
For seeded random number generation, you can create a new Random
object with a specific seed. This allows for reproducible sequences of random numbers, which can be useful for testing or when you need consistent “randomness” across different runs of a program.
Ruby’s random number generation is simpler and more straightforward compared to Go’s, as it doesn’t require separate source and generator objects. However, it still provides powerful functionality for most use cases requiring random number generation.