How do you choose a random word from an array?

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?

···

--
Posted via http://www.ruby-forum.com/.

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

Stefano Crocco wrote:

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!

···

--
Posted via http://www.ruby-forum.com/\.

Stefano Crocco wrote:

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

···

--
Posted via http://www.ruby-forum.com/\.

I like to write it like this:
class Array
  def rand
    at(super(size))
  end
end

···

On 8/15/07, Ilan Berci <coder68@yahoo.com> wrote:

Stefano Crocco wrote:

>
> 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

--

Posted via http://www.ruby-forum.com/\.

Logan Capaldo wrote:

I like to write it like this:
class Array
  def rand
    at(super(size))
  end
end

That's much more cohesive! Thanks for the tip..

ilan

···

--
Posted via http://www.ruby-forum.com/\.