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.
or
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.
After Ruby 2.6
The patch
adds an ability to call bytes
method on Random class directly.
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 ""
.
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox