Pig Latin 练习有效,但仅适用于一个用户输入的单词。不是所有的话

Pig Latin exercise works, but only for one user inputed word. Not all words

我是编程新手,我正在使用 Ruby 作为我的入门语言。下面的代码有效,但如果有人输入了多个单词,则 pigatize 方法仅适用于第一个单词,并将额外的 ay 或 way 添加到最后一个单词。我如何让它应用于用户输入的每个单词?

# If the first letter is a vowel, add "way" to the end
# If the first letter is a consonant, move it to the end and add "ay"

class PigLatin
  VOWELS =  %w(a e i o u)

  def self.pigatize(text)
    if PigLatin.vowel(text[0])
      pigalatin = text + 'way'
    else
      piglatin = text[1..-1] + text[0] + 'ay'
    end
  end

  def self.vowel(first_letter)
    VOWELS.include?(first_letter)
  end
end

puts 'Please enter a word and I will translate it into Pig Latin. Ippyyay!.'
text = gets.chomp
puts "Pigatized: #{PigLatin.pigatize(text)}"

主要是,您需要将输入字符串拆分为单词 with String#split,使用如下表达式:

text.split(' ')

这会生成一个单词数组,您可以使用 .each 块和每个单词的 运行 算法对其进行循环,然后使用 += 和 [= 重新组合它们41=] 最后 + ' '

将这些内容合并到现有代码中如下所示(带注释):

class PigLatin
  VOWELS =  %w(a e i o u)

  def self.pigatize(text)
    # Declare the output string
    piglatin = ''
    # Split the input text into words
    # and loop with .each, and 'word' as the iterator
    # variable
    text.split(' ').each do |word|
      if PigLatin.vowel(word[0])
        # This was misspelled...
        # Add onto the output string with +=
        # and finish with an extra space
        piglatin += word + 'way' + ' ' 
      else
        # Same changes down here...
        piglatin += word[1..-1] + word[0] + 'ay' + ' ' 
      end 
    end 
    # Adds a .chomp here to get rid of a trailing space
    piglatin.chomp
  end 

  def self.vowel(first_letter)
    VOWELS.include?(first_letter)
  end 
end
puts 'Please enter a word and I will translate it into Pig Latin. Ippyyay!.'
text = gets.chomp
puts "Pigatized: #{PigLatin.pigatize(text)}"

除了使用 += 添加到字符串之外,还有其他方法可以处理此问题。例如,您可以使用如下表达式将单词添加到数组中:

# piglatin declared as an array []
# .push() adds words to the array
piglatin.push(word + 'way')

然后在需要输出的时候,使用Array#join将它们与spaces连接回去:

# Reassemble the array of pigatized words into a 
# string, joining the array elements by spaces
piglatin.join(' ')

循环有 .each..do 的替代方法。您可以使用像

这样的 for 循环
for word in text.split(' ')
  # stuff...
end

...但是使用 .each do 更加惯用,更能代表您通常在 Ruby 代码中找到的内容,尽管 for 循环更像是除了 Ruby.

之外,您还可以在大多数其他语言中找到