How do you choose a random word from an array?

B

Bob Sanders

I'm trying to choose a random word from a given array. A little
something like this:

christmas_bin = ["candy", "toys", "songs"]

So then, I'd like to choose a random word from it (e.g. "toys").

I tried christmas_bin.rand, but no luck.

Any ideas?
 
S

Stefano Crocco

Alle mercoled=C3=AC 15 agosto 2007, Bob Sanders ha scritto:
I'm trying to choose a random word from a given array. A little
something like this:

christmas_bin =3D ["candy", "toys", "songs"]

So then, I'd like to choose a random word from it (e.g. "toys").

I tried christmas_bin.rand, but no luck.

Any ideas?

christmas_bin[rand(christmas_bin.size)]

Stefano
 
B

Bob Sanders

Stefano said:
Alle mercoledì 15 agosto 2007, Bob Sanders ha scritto:
I'm trying to choose a random word from a given array. A little
something like this:

christmas_bin = ["candy", "toys", "songs"]

So then, I'd like to choose a random word from it (e.g. "toys").

I tried christmas_bin.rand, but no luck.

Any ideas?

christmas_bin[rand(christmas_bin.size)]

Stefano

You're the best, Stefano! Thank you so much!
 
I

Ilan Berci

Stefano said:
christmas_bin[rand(christmas_bin.size)]
Now to combine what Stefano did with your earlier request:
irb(main):001:0> class Array
irb(main):002:1> def rand; self[Kernel.rand(self.size)]; end
irb(main):003:1> end
=> nil
irb(main):004:0> [1,2,3].rand
=> 3
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top