Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Array::pop_all_randomly (See related posts)

This instance method of the Array class will yield an array's members in a random order, along with their original indices in the array. This is useful for applications such as matching games in Ruby on Rails, for example, where it is desirable to display things randomly while retaining information about their original position in an array.

class Array
  public
  # yields the members of an array in a random order,
  # with original indices.
  #
  # Example:
  #  words = %w(dog cat rat rooster crow)
  #  words.pop_all_randomly { |word, index| puts "#{word} (originally word #{index})" }
  # ...yields...
  #  rat (originally word 2)
  #  rooster (originally word 3)
  #  crow (originally word 4)
  #  cat (originally word 1)
  #  dog (originally word 0)
  def pop_all_randomly
    temp = Array.new(self)
    length.times do |i|
      val = temp[rand(temp.length)]
      temp.delete(val)
      old_index = index(val)
      yield [val, old_index]
    end
  end
end

You need to create an account or log in to post comments to this site.


Click here to browse all 5141 code snippets

Related Posts