Ruby:迭代后返回修改后的字符串

时间:2014-07-29 23:06:10

标签: ruby string loops join apache-pig

所以我一直试图用不同的实例编写猪拉丁方法。但是,最后的join方法只是连接字符串的原始单词,而不是经过迭代的修改后的单词:

def translate(string)
  alphabet = ("a".."z").to_a
  vowels = %w{a e i o u}
  consonant = alphabet - vowels
  words = string.split

  words.each do |word|
    if vowels.include?(word[0])
      word = word + "ay"
    elsif word[0..2] == "sch"
      word = word[3..-1] + word[0..2] + "ay"
    elsif word[0..1] == "qu"
      word = word[2..-1] + word[0..1] + "ay"
    elsif word[1..2] == "qu"
      word = word[3..-1] + word[0..2] + "ay"
    elsif consonant.include?(word[0]) && consonant.include?(word[1]) && consonant.include?(word[2])
      word = "#{word[3..-1]}#{word[0..2]}ay"
    elsif consonant.include?(word[0]) && consonant.include?(word[1])
      word = "#{word[2..-1]}#{word[0..1]}ay"
    elsif consonant.include?(word[0])
      word = "#{word[1..-1]}#{word[0]}ay"
    end
  end

  p words.join(" ") 
end


translate("apple pie")
translate("cherry")
translate("school")
translate("square")
translate("three")
translate("apple")
translate("cat")

这就是它在运行时给我的东西:

"apple pie"
"cherry"
"school"
"square"
"three"
"apple"
"cat"

2 个答案:

答案 0 :(得分:1)

尝试使用地图而不是每个

像这样:

def translate(string)
  alphabet = ("a".."z").to_a
  vowels = %w{a e i o u}
  consonant = alphabet - vowels
  words = string.split

  result = words.map do |word|
    if vowels.include?(word[0])
      word = word + "ay"
    elsif word[0..2] == "sch"
      word = word[3..-1] + word[0..2] + "ay"
    elsif word[0..1] == "qu"
      word = word[2..-1] + word[0..1] + "ay"
    elsif word[1..2] == "qu"
      word = word[3..-1] + word[0..2] + "ay"
    elsif consonant.include?(word[0]) && consonant.include?(word[1]) && consonant.include?(word[2])
      word = "#{word[3..-1]}#{word[0..2]}ay"
    elsif consonant.include?(word[0]) && consonant.include?(word[1])
      word = "#{word[2..-1]}#{word[0..1]}ay"
    elsif consonant.include?(word[0])
      word = "#{word[1..-1]}#{word[0]}ay"
    end
    word
  end

  p result.join(" ") 
end


translate("apple pie")
translate("cherry")
translate("school")
translate("square")
translate("three")
translate("apple")
translate("cat")

我建议您阅读此答案Array#each vs. Array#map 因为它将揭示地图与每个地图之间的差异。你的每个块都返回原始的单词数组,这就是为什么它永远不会改变。

答案 1 :(得分:0)

使用正则表达式和case语句,你可以压缩它:

def pig_latin(word)
  case word
  when /^[aeiou]/ #starts with a vowel
    word + "ay"
  when /^([s?qu|[^aeiou]{1,3})/ #starts with qu, squ or 1-3 consonants
    rep = $1
    word.sub(rep, "") + "#{rep}ay"
  end
end

def translate(string)
  string.split.map { |word| pig_latin(word) }.join " "
end

导致以下测试全部为true

puts translate("apple pie") == "appleay iepay"
puts translate("cherry") == "errychay"
puts translate("school") == "oolschay"
puts translate("square") == "aresquay"
puts translate("three") == "eethray"
puts translate("apple") == "appleay"
puts translate("cat") == "atcay"

请注意,我简化了第二个正则表达式,假设在单词的开头可以在“qu”之前的唯一辅音是“s”(根据/usr/share/dict/words的情况)。