gpt4 book ai didi

ruby - 如果字符串包含元音且按字母顺序排列,则输出字符串

转载 作者:数据小太阳 更新时间:2023-10-29 08:38:19 25 4
gpt4 key购买 nike

我正在进行以下练习:

编写一个方法,ovd(str),它接受一串小写单词并返回一个字符串,该字符串仅包含按字母顺序排列的所有元音(不包括“y”)的单词。元音可以重复(“afoot” 是一个有序的元音词)。如果单词不按字母顺序排列,则该方法不会返回该单词。

示例输出为:

ovd("this is a test of the vowel ordering system") #output=> "this is a test of the system"

ovd("complicated") #output=> ""

下面是我编写的代码,可以完成这项工作,但我想看看是否有更短、更聪明的方法来完成这项工作。我的解决方案似乎太长了。在此先感谢您的帮助。

def ovd?(str) 
u=[]
k=str.split("")
v=["a","e","i","o","u"]
w=k.each_index.select{|i| v.include? k[i]}
r={}
for i in 0..v.length-1
r[v[i]]=i+1
end
w.each do |s|
u<<r[k[s]]
end
if u.sort==u
true
else
false
end

end

def ovd(phrase)
l=[]
b=phrase.split(" ")
b.each do |d|
if ovd?(d)==true
l<<d
end
end
p l.join(" ")
end

最佳答案

def ovd(str)
str.split.select { |word| "aeiou".match(/#{word.gsub(/[^aeiou]/, "").chars.uniq.join(".*")}/) }.join(" ")
end
ovd("this is a test of the vowel ordering system") # => "this is a test of the system"
ovd("complicated") # => ""
ovd("alooft") # => "alooft"
ovd("this is testing words having something in them") # => "this is testing words having in them"

编辑

应OP要求,解释

String#gsub word.gsub(/[^aeiou]/, "") 删除非元音字符,例如 "afloot".gsub(/[^aeiou]/, "") # => "aoo" String#chars将新单词转换为字符数组

"afloot".gsub(/[^aeiou]/, "").chars # => ["a", "o", "o"]

Array#uniq转换仅返回数组中的唯一元素,例如

"afloot".gsub(/[^aeiou]/, "").chars.uniq # => ["a", "o"]

Array#join将数组转换为字符串,将其与提供的参数合并,例如

"afloot".gsub(/[^aeiou]/, "").chars.uniq.join(".*") # => "a.*o"  

#{} 就是 String interpolation和//将内插字符串转换为正则表达式

/#{"afloot".gsub(/[^aeiou]/, "").chars.uniq.join(".*")}/ # => /a.*o/

关于ruby - 如果字符串包含元音且按字母顺序排列,则输出字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20914922/

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