Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
Jan 7 ’11

Random Array Item

From 1.8.7 on, there is the Array#shuffle method.

[1,2,3].shuffle # => [2,1,3]

This makes it extremely easy to write Array#random to pick a random item from an array

class Array
  def random
    shuffle.first
  end
end

[1,2,3,4,5,6,7,8,9].random # => 5
[1,2,3,4,5,6,7,8,9].random # => 1
[1,2,3,4,5,6,7,8,9].random # => 3

This tip was submitted by Justin Baker.

1 note 0 comments

  1. Justin Baker submitted this to rubyquicktips

Comments

You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

blog comments powered by Disqus