Module: Enumerable

Included in:
Xqsr3::Containers::FrequencyMap, Xqsr3::Containers::MultiMap
Defined in:
lib/xqsr3/extensions/enumerable/unique.rb,
lib/xqsr3/extensions/enumerable/detect_map.rb,
lib/xqsr3/extensions/enumerable/collect_with_index.rb

Instance Method Summary collapse

Instance Method Details

#collect_with_index(base = 0) ⇒ Object

Two-parameter #collect, where the second parameter is a #base-based index, which increments by 1 for each enumerated element.



57
58
59
60
61
62
63
64
65
66
67
# File 'lib/xqsr3/extensions/enumerable/collect_with_index.rb', line 57

def collect_with_index(base = 0)

	a = []

	self.each_with_index do |element, index|

		a.push yield(element, base + index)
	end

	a
end

#detect_map(&block) ⇒ Object

Note:

The block is required (for technical reasons), and must have

The Enumerable#detect method provides a way to detect the presence of a particular value in a collection. The only constraint is that you get back the object unchanged.

The Enumerable#map method provides a way to transform the contents of a collection. The only constraint is that you get back another collection.

This extension method, Enumerable#detect_map combines the features of both, in that it detects the presence of a particular value in a collection and transform the detected value.

[ 1, 2, 3 ].detect_map { |v| -2 * v if v > 2 } # => -6

{ :ab => 'cd', :ef => 'gh' }.detect_map { |k, v| v.upcase if k == :ef } # => 'GH'

arity 1 for sequences or 2 for associations



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/xqsr3/extensions/enumerable/detect_map.rb', line 70

def detect_map &block

	case block.arity
	when 1

		self.each do |v|

			r = yield(v) and return r
		end
	when 2

		self.each do |k, v|

			r = yield(k, v) and return r
		end
	else

		raise ArgumentError, "detect_map requires block with arity of 1 (for sequences) or 2 (for associations); block with arity #{block.arity} given to instance of #{self.class}"
	end

	nil
end

#unique(&block) ⇒ Object

Removes all duplicate elements in a sequence subject to an optional two-parameter block in order to return an array containing unique elements



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/xqsr3/extensions/enumerable/unique.rb', line 58

def unique(&block)

	if not block

		return unique { |a, b| a == b }
	else

		if block.arity != 2

			raise ArgumentError, "block requires two parameters"
		end

		ar	=	self.to_a

		return ar if ar.length < 2

		ar	=	ar.clone

		i	=	0

		while i < ar.length do

			j = i + 1

			while j < ar.length do

				if yield ar[i], ar[j]

					ar.delete_at(j)
				else

					j = j + 1
				end
			end

			i = i + 1
		end

		return ar
	end
end