Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a a really big Random integer in Ruby?

I want to generate a 64 bit integer in ruby. I know in Java you have longs, but I am not sure how you would do that in Ruby. Also, how many charecters are in a 64 bit number? Here is an example of what I am talking about... 123456789999.

@num = Random.rand(9000) + Random.rand(9000) + Random.rand(9000)

But i believe this is very inefficient and there must be a simpler and more concise way of doing it.

Thanks!

like image 830
user2351234 Avatar asked Aug 01 '13 18:08

user2351234


1 Answers

rand can take a range as argument:

p a = rand(2**32..2**64-1) # => 11093913376345012184
puts a.class #=> Bignum

From the doc: Bignum objects hold integers outside the range of Fixnum. Bignum objects are created automatically when integer calculations would otherwise overflow a Fixnum. When a calculation involving Bignum objects returns a result that will fit in a Fixnum, the result is automatically converted...

like image 145
steenslag Avatar answered Sep 30 '22 05:09

steenslag