Search code examples
rubyruby-on-rails-4randommaxlength

The difference between rand(1e9...1e10).to_i and rand.to_s[2..11].to_i


In Ruby 2.3.0, when I do rand.to_s[2..11].to_i to insert something multiple times in a loop in the ActiveRecord, which validates length: {maximum: 10, minimum: 10}. I got an error after some iteration that the length validation failed! And when I do rand(1e9...1e10).to_i in the same scenario, it solves the problem. I want to know what's the difference between these two.


Solution

  • #rand without arguments generates a random number between 0 and 1.

    This can be 0.01111111111111. to_s[2..12] then takes the first 10 digits after the decimal dot.

    '01'.to_i # => 1
    

    Hence you might get length less than 10.