我正在进行以下练习:
编写一个方法,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 Converts 仅返回数组中的唯一元素,例如
"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/