Ruby 2.6 adds Random.bytes method

Ruby 2.6.0-preview2 has been released recently. Random.bytes method was introduced with the release. This is equivalent to Random::DEFAULT.bytes. The feature returns random bytes based on the length argument passed to it.

We need Ruby 2.6.0 version to try out this feature.

Install Ruby 2.6.0

As we have previw versions released, we can install ruby-2.6.0-preview1 or ruby-2.6.0-preview2 using RVM as given below.

rvm install 2.6.0-preview1

or

rvm install 2.6.0-preview2
Random.bytes

Syntax: Random.bytes(length) - where length is an integer argument. Returns random binary string for the length / size argument passed to it.

Prior to Ruby 2.6

When we want to get random binary string, we had to call bytes method on an object of Random class.

Random.new.bytes(1)
# => "\x7F"
After Ruby 2.6

The patch adds an ability to call bytes method on Random class directly.

Random.bytes(1)
# => "\xC0"

As we can observe, it returns random binary string similar to method Random::DEFAULT.bytes. If we call Random.bytes(0), it always returns an empty string "".