-
Notifications
You must be signed in to change notification settings - Fork 67
/
hash.rb
62 lines (57 loc) · 2.62 KB
/
hash.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
############################################################################
# Copyright 2009-2019 Benjamin Kellermann #
# #
# This file is part of Dudle. #
# #
# Dudle is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Affero General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# Dudle is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or #
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public #
# License for more details. #
# #
# You should have received a copy of the GNU Affero General Public License #
# along with dudle. If not, see <http://www.gnu.org/licenses/>. #
############################################################################
class Hash
####################################################
# compare self with other hash #
# in the order of fieldarray #
# {1=>a,2=>b}.compare_by_values({1=>c,2=>d},[2,1]) #
# -> compares b,d and afterwards a,c #
####################################################
def compare_by_values(other, fieldarray)
return 0 if fieldarray.size == 0
return 1 if self[fieldarray[0]].nil?
return -1 if other[fieldarray[0]].nil?
if self[fieldarray[0]] == other[fieldarray[0]]
if fieldarray.size == 1
return 0
else
return self.compare_by_values(other, fieldarray[1,fieldarray.size-1])
end
else
self[fieldarray[0]] <=> other[fieldarray[0]]
end
end
end
if __FILE__ == $0
require "test/unit"
class Hash_test < Test::Unit::TestCase
def test_compare_by_values
a = {1 =>1, 2=>2, 3=>3}
b = {1 =>1, 2=>2, 3=>2}
c = {1 =>1, 2=>3, 3=>3}
d = {1 =>1, 2=>3}
assert_equal( 0,a.compare_by_values(a,[1,2,3]))
assert_equal( 1,a.compare_by_values(b,[1,2,3]))
assert_equal(-1,a.compare_by_values(c,[1,2,3]))
assert_equal(-1,c.compare_by_values(d,[1,2,3]))
assert_equal( 1,d.compare_by_values(c,[1,2,3]))
assert_equal( 0,d.compare_by_values(c,[]))
end
end
end