Entries RSS Comments RSS

Defining Useful Methods in Ruby: Adding a rand method to the Array Class

The ‘rand’ method in Ruby is a method of the Kernel class that generate a random float between 0 and 1 (and thus will always round down to 0 when converting to an int.) Being a new Ruby developer, I decided to make an array and try to pull a random element like so:

@name=%w[bob, judy, don, john]
@get_random_name = @name[rand]

But this will always return ‘bob’, the 0th element of the array.

Instead, to pull a random element from an array (of any length), you need:

@get_random_name= @name[rand(@name.length)]

But that’s icky and unRubyish, and Ruby really SHOULD have a rand method for the Array class, shouldn’t it? So let’s make one, because we can! :)

class Array
def rand
self[super(self.length)]
end
end

@name.rand will now return a random element from the array. Awesome.

Tags:

Leave a Reply