user2351234
user2351234

Reputation: 975

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!

Upvotes: 5

Views: 3002

Answers (1)

steenslag
steenslag

Reputation: 80065

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...

Upvotes: 12

Related Questions