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


rvm install 2.6.0-preview2


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.

# => "\x7F"

After Ruby 2.6

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

# => "\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 "".


Akshay Mohite

Hi there! I am a Ruby on Rails & ReactJS Enthusiast, building some cool products at DTree Labs.

Read More
Buy me a coffee