Module: Enumerable

Included in:
ObjectSpace
Defined in:
lib/extra/enumerable.rb

Instance Method Summary collapse

Instance Method Details

#+@Object

Shorthand to get the size of the enumerable object in an array state.

Example: +[:a, :b, :c] #=> 3

Returns: Integer size



19
20
21
# File 'lib/extra/enumerable.rb', line 19

def +@
	to_a.size
end

#random(how_many = 1) ⇒ Object

Get a random element from the array.

Example: [:a, :b, :c].random #=> :b

Returns: Random object(s) or nil.



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/extra/enumerable.rb', line 29

def random(how_many = 1)
	objects = {}
	array   = to_a

	# Let's just skip to nil if more than existent entries was requested.
	return if array.size < how_many

	# This is a longer, more efficient way than sorting the entire array.
	how_many.times do
		index = rand(array.size)
		redo if objects.keys.include? index
		objects[index] = array[index]
	end

	how_many == 1 ? objects.values[0] : objects.values
end

#random=(obj) ⇒ Object

Randomly replaces an object in the array.

Example: a = [1, 2, 3]; a.random = 256; a #=> [256, 2, 3]

Returns: Object



52
53
54
# File 'lib/extra/enumerable.rb', line 52

def random=(obj)
	array, array[rand(array.size)] = to_a, obj
end

#to_hashObject

Get a hash representation of an array. The number of flattened array elements has to be even in order for this to work.

Example: [:foo, :bar, :baz, :qux].to_hash #=> {:foo => :bar, :baz => :qux}

Returns: Hash object



9
10
11
# File 'lib/extra/enumerable.rb', line 9

def to_hash
	Hash[*to_a.flatten]
end