-
Notifications
You must be signed in to change notification settings - Fork 1
/
Ruby - rmvDuplicates.txt
69 lines (36 loc) · 1.06 KB
/
Ruby - rmvDuplicates.txt
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
take an array of integers and return an array with all the unique values in the proper order.
def unique(integers)
uniArr = []
for i in integers do
unless uniArr.include?(i)
uniArr << i
end
end
uniArr
end
unique([1,1,2,3,5])
=> [1,2,3,5]
unique([7,7,7,7,7,7,7,7,7,7,7,7,7,1])
=> [7,1]
- - - - - - - alt - - - - - - - -
# Define the unique method that removes duplicates
def unique(integers)
new=[]
integers.each {|x| new.push(x) unless new.include?(x) }
new
end
- - - - - - - better alt - - - - - - - -
# Define the unique method that removes duplicates
def unique(integers)
integers.to_set.to_a
end
- - - - - - - best alt - - - - - - - -
def unique(integers)
integers & integers
end
^^^explanation^^^
“&” is ‘set intersection’
“ary & other_ary”
=> new_ary
Set Intersection — Returns a new array containing elements common to the two arrays, excluding any duplicates. The order is preserved from the original array.
It compares elements using their hash and eql? methods for efficiency.