如何重新排列字符串中的所有元音?

Reichertjalex

我正在尝试创建一种方法,以尽可能有效地对字符串中的所有元音进行重新排序。例如:

"you are incredible." 退货 "yae ere incridoblu."

这是我想出的:

def vowel_orderer(string)
  vowels = ["a","e","i","o","u"]
  ordered_vowels = string.scan(/[aeiou]/).sort
  ordered_string = []

  i = 0
  j = 0
  while i < string.length
    if vowels.include?(string[i])
      ordered_string << ordered_vowels[j]
      j += 1
    else
      ordered_string << string[i] unless vowels.include?(string[i])
    end
    i += 1
  end

  puts ordered_string.join

end

我觉得应该有一种更短的方法来完成此任务,例如使用gsub

好的
string = "you are incredible."
ordered_vowels = string.scan(/[aeiou]/).sort
string.gsub(/[aeiou]/){ordered_vowels.shift} # => "yae ere incridoblu."

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章