Ruby: Difference between Random#rand and Kernel#rand
random, ruby
Solution
They behave the same when called with a `Range`, but differently in several other cases.
- 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`).
- When called with 0, `Random#rand` raises `ArgumentError`, while `Kernel#rand` just behave as if you called it without any argument.
- 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`.
Problem
Is there is really difference between Random#rand and Kernel#rand? From what i can see they use different 'C' functions.