Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate unique initial strings from array of strings

I have a very long array of strings. For example:

["Abyssal Specter", "Air Elemental", "Aladdin's Ring", "Ambition's Cost", "Anaba Shaman", "Angel of Mercy", "Angelic Page", "Archivist", "Ardent Militia", "Avatar of Hope", "Aven Cloudchaser","Aven Fisher"]

Now this array must be passed to a method which should return

[["Abyssal Specter","Ab"], ["Air Elemental", "Ai"], ["Aladdin's Ring","Al"], ["Ambition's Cost","Am"], ["Anaba Shaman","Ana"], ["Angel of Mercy","Angel "], ["Angelic Page","Angeli"], ["Archivist","Arc"], ["Ardent Militia","Ard"], ["Avatar of Hope","Ava"], ["Aven Cloudchaser","Aven C"],["Aven Fisher","Aven F"]]

The method should return the unique initials of each string in the array.

For instance, "Abyssal Specter" should return "Ab" as there is no other string starting with "Ab". Similarly for "Air Elemental" to "Ai". But "Aven Cloudchaser" should return "Aven C", as there is a string "Aven Fisher". In short, it should just generate the unique string initials.

like image 891
Gagan Avatar asked Nov 26 '25 12:11

Gagan


1 Answers

Abbrev in Standard Lib does exactly that:

require 'abbrev'

ar = ["Abyssal Specter", "Air Elemental", "Aladdin's Ring", "Ambition's Cost", "Anaba Shaman", "Angel of Mercy", "Angelic Page", "Archivist", "Ardent Militia", "Avatar of Hope", "Aven Cloudchaser","Aven Fisher"]
p ar.abbrev.invert.to_a

# [["Abyssal Specter", "Ab"], ["Air Elemental", "Ai"], ["Aladdin's Ring", "Al"], ["Ambition's Cost", "Am"], ["Anaba Shaman", "Ana"], ["Angel of Mercy", "Angel "], ["Angelic Page", "Angeli"], ["Archivist", "Arc"], ["Ardent Militia", "Ard"], ["Avatar of Hope", "Ava"], ["Aven Cloudchaser", "Aven C"], ["Aven Fisher", "Aven F"]]
like image 94
steenslag Avatar answered Nov 29 '25 12:11

steenslag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!