0

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

"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

4

2 回答 2

3
string = "you are incredible."
ordered_vowels = string.scan(/[aeiou]/).sort
string.gsub(/[aeiou]/){ordered_vowels.shift} # => "yae ere incridoblu."
于 2013-11-14T07:20:09.820 回答
0
def vowel_orderer_gsub(string)
  ordered_vowels = string.scan(/[aeiou]/).sort { |x,y| y <=> x }
  puts string.gsub(/[aeiou]/) { |match| ordered_vowels.pop }
end

1.9.3p448 :128 >   vowel_orderer( "you are incredible." )
# yae ere incridoblu.
# => nil
1.9.3p448 :129 > vowel_orderer_gsub( "you are incredible." )
# yae ere incridoblu.
于 2013-11-14T07:57:44.607 回答