Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Difference between Random#rand and Kernel#rand

Tags:

random

ruby

Is there is really difference between Random#rand and Kernel#rand?

From what i can see they use different 'C' functions.

like image 959
Leonid Bugaev Avatar asked Oct 06 '22 04:10

Leonid Bugaev


2 Answers

They behave the same when called with a Range, but differently in several other cases.

  1. When called with a negative integer -n (like -3), Random#rand raises ArgumentError, while Kernel#rand just behave as if you called it with n (by (-n).to_int.abs).
  2. When called with 0, Random#rand raises ArgumentError, while Kernel#rand just behave as if you called it without any argument.
  3. When called with Float n, Random#rand returns a float between 0 and n (as expected). Kernel#rand do an n.to_int.abs conversion, so for example rand(-1.9) is equivalent to rand(1), which always returns 0; rand(0.1) is equivalent to rand(0) and thus equivalent to rand.

It seems that Random#rand (and also Random::rand of course) is more robust than Kernel#rand for strange parameter. More information in documentation for Kernel#rand and Random#rand.

like image 79
Franklin Yu Avatar answered Oct 10 '22 03:10

Franklin Yu


It looks like a slightly different API, but both seem to leave the actual generating to the genrand_real function.

like image 26
steenslag Avatar answered Oct 10 '22 04:10

steenslag