gpt4 book ai didi

ruby - 从字符串数组生成唯一的初始字符串

转载 作者:数据小太阳 更新时间:2023-10-29 07:56:07 26 4
gpt4 key购买 nike

我有一个很长的字符串数组。例如:

["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"。简而言之,它应该只生成唯一的字符串首字母。

最佳答案

标准库中的缩写正是这样做的:

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"]]

关于ruby - 从字符串数组生成唯一的初始字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21367627/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com