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.

require 'random'

# For example, `Random.rand(100)` returns a random integer n,
# 0 <= n < 100.
print Random.rand(100), ","
print Random.rand(100)
puts

# `Random.rand` returns a float f,
# 0.0 <= f < 1.0.
puts Random.rand

# This can be used to generate random floats in
# other ranges, for example 5.0 <= f' < 10.0.
print (Random.rand * 5) + 5, ","
print (Random.rand * 5) + 5
puts

# If you want a known seed, create a new
# Random object with a specific seed.
r2 = Random.new(42)
print r2.rand(100), ","
print r2.rand(100)
puts

# Using the same seed will produce the same sequence of numbers.
r3 = Random.new(42)
print r3.rand(100), ","
print r3.rand(100)
puts

Some of the generated numbers may be different when you run the sample.

$ ruby random_numbers.rb
68,56
0.8090228139659177
5.840125017402497,6.937056298890035
94,49
94,49

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.