ruby:在迭代后返回修改过的字符串

fafcakar  于 2021-06-21  发布在  Pig
关注(0)|答案(2)|浏览(366)

所以我一直在尝试用不同的示例来编写pig-latin方法。但是,最后的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"
rmbxnbpk

rmbxnbpk1#

使用正则表达式和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 ).

8hhllhi2

8hhllhi22#

尝试使用map而不是each
像这样:

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")

我建议阅读这个答案数组#each vs.array#map,因为它将阐明map和each之间的区别。您的每个块都返回原始单词数组,因此它从未更改。

相关问题