Search code examples
rubystringbitvariable-length

Ruby: How to generate strings of variable bits length with only alphanumeric characters?


I am trying to solve the following problem using Ruby:

I have a requirement to generate strings with variable bits length which contain only alphanumeric characters.

Here is what I have already found:

Digest::SHA2.new(bitlen = 256).to_s
# => "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"

It does exactly what I need, but it accepts only 256, 384, and 512 as bitlen.

Does anybody aware of any alternatives?

Thanks in advance.

Update

  1. One byte = collection of 8 bits.
  2. Every alphanumeric character occupies 1 byte according to String#bytesize.
('a'..'z').chain('A'..'Z').chain('0'..'9').map(&:bytesize).uniq
# => [1]
  1. Based on the facts mentioned above, we can suppose that

    • SecureRandom.alphanumeric(1) generates an alphanumeric string with 8 bits length.
    • SecureRandom.alphanumeric(2) generates an alphanumeric string with 16 bits length.
    • SecureRandom.alphanumeric(3) generates an alphanumeric string with 24 bits length.
    • And so on...
  2. As a result, @anothermh's answer can be considered as an acceptable solution.


Solution

  • Use SecureRandom.

    First, make sure you require it:

    require 'securerandom'
    

    Then you can generate values:

    SecureRandom.alphanumeric(10)
    => "hxYolwzk0P"
    

    Change 10 to whatever length you require.

    It's worth pointing out that the example you used was returning not alphanumeric but hexadecimal values. If you specifically require hex then you can use:

    SecureRandom.hex(10)
    => "470eb1d8daebacd20920"