[#3986] Re: Principle of least effort -- another Ruby virtue. — Andrew Hunt <andy@...>

> Principle of Least Effort.

14 messages 2000/07/14

[#4043] What are you using Ruby for? — Dave Thomas <Dave@...>

16 messages 2000/07/16

[#4139] Facilitating Ruby self-propagation with the rig-it autopolymorph application. — Conrad Schneiker <schneik@...>

Hi,

11 messages 2000/07/20

[ruby-talk:03775] Array.pick

From: Aleksi Niemel<aleksi.niemela@...>
Date: 2000-07-03 19:45:16 UTC
List: ruby-talk #3775
I've found following snippet quite handy. Dunno if there's wider need for
this.

class Array
	def pick( count = -1 )
		if count >= 0
			ary = []
			count.times do
				ary << self.delete_at( rand( self.length ) )
			end
			return ary
		end
		self.delete_at( rand( self.length ) )
	end
end

require 'xmp'

xmp <<-EOS
a = (0...10).to_a
b = []

3.times do b << a.pick end

b

a.pick(0)
a.pick(1)
a.pick(3)

a
EOS

################
Outputs:

a = (0...10).to_a
    #=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = []
    #=> []

3.times do b << a.pick end
    #=> 3

b
    #=> [9, 3, 5]

a.pick(0)
    #=> []
a.pick(1)
    #=> [7]
a.pick(3)
    #=> [6, 0, 2]

a
    #=> [1, 4, 8]

Ps. guess why I found EOS\n -feature ?)

	- Aleksi

In This Thread

Prev Next