Why isn't Ruby's
rand method defined like this?
alias original_rand rand
def rand(arg1=nil, arg2=nil)
if !arg1.kind_of?(Enumerable) && arg2 == nil
original_rand(arg1)
elsif arg1.kind_of? Enumerable
as_array = arg1.to_a
as_array[original_rand(as_array.length)]
elsif arg1 != nil
arg1 + original_rand(arg2)
end
end
puts rand
puts rand(6)
puts rand(10..11)
puts rand(2,4)
puts rand(['a', 'b', 'c'])
Quite some time ago I couldn't find anything on how to do get a
random number in Ruby. After having looked at Google and
Ruby's Math class I didn't find anything, so I just tried
rand to see what would happen. Of course, I was pleasantly surprised that it worked. I did some experimenting to see how it worked, and wrote the post in hopes of helping others new to Ruby who would have similar trouble finding the answer.
A recent commenter on that post yesterday mentioned his surprise at how "low-level" the behavior is.
Most things in Ruby are obvious and go along with the unwritten rule of least surprise. Not accepting Ranges, in my opinion, goes against that.
Update: Updated the redefinition of
rand to include suggestions and fix bugs described by a2800276 in the comments.
Update 2: By calling the current implementation "low-level" I'm saying that having the programmer deal with the math involved in getting a range of integers is what I consider low-level.
Update 3: There is discussion on
the Ruby subreddit about whether this method would make more sense on Enumerable than Kernel.
I think Kernel is an odd place for rand to begin with, but I can see the point. The problem is that my own brain applies some almost circular reasoning as to where it should be (as described in the comments over at reddit).
Hey! Why don't you make your life easier and subscribe to the full post
or short blurb RSS feed? I'm so confident you'll love my smelly pasta plate
wisdom that I'm offering a no-strings-attached, lifetime money back guarantee!
Leave a comment
There are no comments for this entry yet.
Leave a comment