Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/chisel/ruby/array.rb

Instance Method Summary collapse

Instance Method Details

#sort_by_method(method_name, ascending = true) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
# File 'lib/chisel/ruby/array.rb', line 2

def sort_by_method(method_name, ascending=true)
	method_name = method_name.to_sym
	self.sort do |left, right|
		if left.respond_to?(method_name) and right.respond_to?(method_name)
			if ascending
				left.public_send(method_name) <=> right.public_send(method_name)
			else
				right.public_send(method_name) <=> left.public_send(method_name)
			end
		else
			raise "Could not sort items #{left} and #{right}. They do not both respond to method '#{method_name.to_s}'"
		end
	end
end

#unique(method_name) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/chisel/ruby/array.rb', line 17

def unique(method_name)
	method_name = method_name.to_sym
	values = []
	
	self.each do |item|
		if item.respond_to?(method_name)
			value = item.send(method_name)
			values << value unless values.index(value)
		else
			raise "Could not pick out unique items: #{item} does not respond to method '#{method_name}'"
		end
	end
	
	values
end