gpt4 book ai didi

ruby - 在 Ruby 中将元音更改为其在字符串中的索引号的程序

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

这是一个将元音转换成其索引的程序:

 def vowel_2_index(string)  
return '' if string.nil?
arr = string.enum_for(:scan,/[aeiou]/i).map {Regexp.last_match.begin(0) }
s_arr = arr.map{|x| x+1 }
arr.each_with_index{|x,y| string[x] = s_arr[y].to_s}
string
end

谁能告诉我为什么它未能通过“Codewars 是世界上最好的网站”?

当我尝试通过这样的测试用例时:

Test.assert_equals(vowel_2_index('Codewars is the best site in the world'),'C2d4w6rs 10s th15 b18st s23t25 27n th32 w35rld') 

它的输出是这样的:

"C2d4w6rs 10s t15e18bes232527ite32i35 the world"

最佳答案

如您所见,当您开始用它们的位置替换元音时,它在位置为单个数字(即 15)时起作用,但是当位置变为2 位数(10 和更大)所有找到的索引开始移动并且 arr 信息不再正确。

我建议使用 gsub ,因为你想做一个全局搜索和替换,你几乎做对了:

str = 'Codewars is the best site in the world'    
str.gsub(/[aeiou]/) { |item| Regexp.last_match.begin(0) + 1 }
# => "C2d4w6rs 10s th15 b18st s23t25 27n th32 w35rld"

关于ruby - 在 Ruby 中将元音更改为其在字符串中的索引号的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33320617/

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