我正在研究一种将句子翻译成猪拉丁语的函数,但是当我将输入视为“樱桃”这样的东西时,它应该给出“errychay”,只有当我返回newWord + block时它才会给出“erryay” +'ay',如果我只是把它,我会得到一个空值的数组。
以元音开头的单词显然很好(E.G. apple)
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(' ')
端
答案 0 :(得分:0)
问题是block = ''
发生在for
循环的每次迭代开始时。因此,阻止不断重置为''
,从而导致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
答案 1 :(得分:0)
替代方法虽然你仍然需要找到一种处理混合的方法,如(' ch','等等)
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
答案 2 :(得分:0)
3件事,你确定的那个是块=&#39;&#39;需要在循环之外发生。另外两个是:
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"
运行它:
{{1}}