shin
shin

Reputation: 32721

How to eliminate items with the same last letter in Ruby

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

Answers (2)

Cary Swoveland
Cary Swoveland

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

sawa
sawa

Reputation: 168101

["cA", "bA", "aA", "bB", "aC", "cC", "dD", "aD"]
.group_by{|s| s[-1]}.values.map(&:first)
# => ["cA", "bB", "aC", "dD"]

Upvotes: 3

Related Questions