This is a personal memo.
You can use the uniq method to eliminate duplicate elements.
--Non-destructive processing. --Using blocks, you can compare after processing each element --In case of duplication, the first element remains. (Delete the element behind)
python
arr = [1, 4, 5, 3, 5, 6, 1, 3, 2, 2, 1, 1, 1]
arr.uniq
=> [1, 4, 5, 3, 6, 2]
##Non-destructive confirmation
p arr
=> [1, 4, 5, 3, 5, 6, 1, 3, 2, 2, 1, 1, 1]
・object.uniq{|variable|processing}
For example, for an element containing a character string, use to_s
to make all the elements into a character string and then compare them.
python
arr1 = [1, 3, 2, "2", "3", 1]
arr1.uniq{|i| i.to_s}
=> [1, 3, 2]
Original value | 1 | 3 | 2 | "2" | "3" | 1 |
---|---|---|---|---|---|---|
After treatment | "1" | "3" | "2" | "2" | "3" | "1" |
Remaining elements | ○ | ○ | ○ | × | × | × |
Therefore, the output will be the original value [1, 3, 2]
corresponding to the first one without duplication.
・object.uniq{|Variable 1,Variable 2|processing}
--Block is required
--Two variables are required. The key is entered in variable 1 and the value is entered in variable 2.
--Since the output will be an array, use to_h
to return it to an object (symbol).
python
obj = {:a=>1, :b=>2, :c=>3, :d=>2, :f=>3}
obj2 = obj.uniq{|x,y| y}
=> [[:a, 1], [:b, 2], [:c, 3]]}
obj2.to_h
=> {:a=>1, :b=>2, :c=>3}
python
obj = {:a=>1, :b=>2, :c=>3, :d=>2, :f=>3}
obj.uniq{|x,y| y}.to_h{|k ,v| [k.to_s, v]}
=> {"a"=>1, "b"=>2, "c"=>3}
Recommended Posts