ruby中的piglatin不返回任何内容

m4pnthwp  于 2021-06-21  发布在  Pig
关注(0)|答案(3)|浏览(395)

我正在开发一个函数,它可以将句子翻译成pig拉丁语,但是当我输入类似“cherry”的内容时,它会给出“errychay”,只有在我返回newword+block+ay的情况下,如果我把它放进去,我会得到一个空值数组。
以元音开头的单词显然很好用(例如苹果)

def translate(s)
v = %w{a e i o u}
s = s.split.map! do |word|
    if v.include? word[0]
        word + 'ay' 
    else
        for letter in 0...word.length 
            block = ''
            if !(v.include? word[letter] )
                block += word[letter]
            else
                newWord = word.slice(letter,word.length - 1)
                newWord + block + 'ay' 
                block = ''
                break
            end
        end
    end
end
s.join(' ')

结束

4si2a6ki

4si2a6ki1#

问题是 block = '' 在每个迭代的开始时发生 for 循环。所以,block一直被重置为 '' ,导致 newWord + '' + 'ay' 这就是你得到的。你可以通过拉出 block = '' 所以它只发生一次,在你 for 回路:

def translate(s)
  v = %w{a e i o u}
  s = s.split.map! do |word|
    if v.include? word[0]
      word + 'ay' 
    else
      block = ''
      for letter in 0...word.length 
        if !(v.include? word[letter] )
          block += word[letter]
        else
          newWord = word.slice(letter,word.length - 1)
          break (newWord + block + 'ay')
        end
      end
    end
  end
  s.join(' ')
end

编辑:我忍不住要重构一下你的代码。我主要想提出一种不需要人工操作的方法 break 从循环中退出。诀窍是定义小的辅助函数。

def vowel?(letter)
  %w{a e i o u}.include? letter
end

def translate(word)
  if vowel? word[0]
    word + 'ay' 
  else
    head = ''
    for i in 0...word.length 
      unless vowel? word[i]
        head += word[i]
      else
        tail = word.slice(i, word.length - 1)
        return tail + head + 'ay'
      end
    end
  end
end

def translate_sentence(s)
  s.split.map {|word| translate word}.join(' ')
end
zsbz8rwp

zsbz8rwp2#

另一种方法,尽管您仍然需要找到一种方法来处理类似('ch','th'等)的混合

def to_pig_latin(sentence)
   v = %w(a e i o u)
   sentence.split.map{|word| v.include?(word[0].downcase) ? word << 'ay' : word[1..-1] << word[0] << 'ay'}.join(' ')
 end
oxiaedzo

oxiaedzo3#

有三件事,您标识的块=''需要发生在循环之外。另外两个是:

else
  newWord = word.slice(letter,word.length - 1)
  newWord + block + 'ay'                       # this does nothing
  block = ''
  break                                        # nothing makes it back to map
end

我想你的意思是 newWord + block + 'ay' 返回的值 map 打电话,不是。试试这个:

def translate(s)
  v = %w{a e i o u}
  s = s.split.map! do |word|
    if v.include? word[0]
      word + 'ay' 
    else
      block = ''
      for letter in 0...word.length 
        if !(v.include? word[letter] )
          block += word[letter]
        else
          newWord = word.slice(letter,word.length - 1)
          newWord += block + 'ay' 
          block = ''
          break(newWord)
        end
      end
    end
  end
  s.join(' ')
end

p translate('apple')
p translate('cherry')
p translate('fancy')

运行它:

(nick@thin)-(~)
(508)⚡️ ruby Desktop/test.rb 
"appleay"
"errychay"
"ancyfay"

相关问题