Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby/array/random.rb,
lib/ruby/array/columnize.rb

Constant Summary collapse

ColumnizeDefaults =
{
	:prepend     => "",
	:orientation => :vertical,
	:spacing     => 1
}

Instance Method Summary collapse

Instance Method Details

#columnize(columns = nil, opts = {}) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/ruby/array/columnize.rb', line 16

def columnize(columns=nil, opts={})
	pre, ori, space = ColumnizeDefaults.merge(opts).values_at(:prepend, :orientation, :spacing)
	columns       ||= 2
	numrows         = length.quo(columns).ceil
	sizes, print    = Array.new(columns) { [] }, Array.new(numrows) { [] }

	if ori == :vertical then
		(self+Array.new(numrows*columns-length,"")).each_with_index { |e,i|
			sizes[i.div(numrows)] << e
			print[i%numrows]      << e
		}
	else
		(self+Array.new(numrows*columns-length,"")).each_with_index { |e,i|
			sizes[i%columns]      << e
			print[i.div(columns)] << e
		}
	end

	sizes  = sizes.map { |e| e.map { |f| f.length }.max+space }
	format = "#{pre}%-#{sizes.join('s %-')}s"
	print.map { |e| format % e }.join("\n")
end

#random(n = nil) ⇒ Object

Get a random element of this array With an argument it gets you n elements without no index used more than once



4
5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/ruby/array/random.rb', line 4

def random(n=nil)
	unless n then
		at(rand(length))
	else
		raise ArgumentError unless Integer === n and n.between?(0,length)
		ary = dup
		l   = length
		n.times { |i|
			r = rand(l-i)+i
			ary[r], ary[i] = ary[i], ary[r]
		}
		ary.first(n)
	end
end