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

时间:2013-11-14 07:10:33

标签: ruby string

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

"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的内容?

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分: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.