我有很长的字符串数组。例如:
["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"]
现在必须将此数组传递给应返回
的方法[["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"]]
该方法应该返回数组中每个字符串的唯一首字母。
例如,"Abyssal Specter"
应返回"Ab"
,因为没有其他字符串以"Ab"
开头。同样适用于"Air Elemental"
到"Ai"
。但是"Aven Cloudchaser"
应该返回"Aven C"
,因为有一个字符串"Aven Fisher"
。简而言之,它应该只生成唯一的字符串首字母。
答案 0 :(得分:4)
标准Lib中的缩写就是这样:
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"]]