-
Notifications
You must be signed in to change notification settings - Fork 49
/
array.rb
42 lines (39 loc) · 857 Bytes
/
array.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# The Array class we all know and love.
#
class Array # :nodoc:all
# Cluster-uniqs equal neighborly elements.
#
# Returns a copy.
#
def clustered_uniq
self.inject([]) do |result, element|
result << element if element != result.last
result
end
end
# Around 10% faster than the above.
#
# Returns a copy.
#
def clustered_uniq_fast
result = []
self.inject(nil) do |last, element|
if last == element
last
else
result << element && element
end
end
result
end
# Sort the array using distance from levenshtein.
#
# Will raise if encounters not to_s-able element.
#
def sort_by_levenshtein! from
from = from.to_s
sort! do |this, that|
Text::Levenshtein.distance(this.to_s, from) <=> Text::Levenshtein.distance(that.to_s, from)
end
end
end