Reputation: 32721
I want to delete elements which have the same last letter. For example the following input has cA, bA and aA. All have A at the end. I want to keep only the first one.
aC and cC have the same C and I want to keep aC, the first one etc.
Input
arr = ["cA", "bA", "aA", "bB", "aC", "cC", "dD", "aD"]
desired out put
["cA", "bB", "aC", "dD"]
I tried this but it gives nil.
arr = ["cA", "bA", "aA", "bB", "aC", "cC", "dD", "aD"]
def deletesamesuffix(arr)
arr.reject { |e| e.inculde? e[1]
end
deletesamesuffix(arr)
Upvotes: 0
Views: 53
Reputation: 110675
Another way:
Code
arr.map { |str| str[-1] }.uniq.map { |c| arr.find { |s| s[-1] == c } }
Explanation
a = arr.map { |str| str[-1] }
#=> ["A", "A", "A", "B", "C", "C", "D", "D"]
b = a.uniq
#=> ["A", "B", "C", "D"]
b.map { |c| arr.find { |s| s[-1] == c } }
#=> ["cA", "bB", "aC", "dD"]
Upvotes: 0
Reputation: 168101
["cA", "bA", "aA", "bB", "aC", "cC", "dD", "aD"]
.group_by{|s| s[-1]}.values.map(&:first)
# => ["cA", "bB", "aC", "dD"]
Upvotes: 3