【问题标题】:Pig Latin exercise works, but only for one user inputed word. Not all wordsPig Latin 练习有效,但仅适用于一个用户输入的单词。不是所有的词
【发布时间】:2015-03-31 04:32:27
【问题描述】:

我是编程新手,我正在使用 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)}"

【问题讨论】:

    标签: ruby arrays each


    【解决方案1】:

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

    text.split(' ')
    

    这会产生一个单词数组,您可以使用 .each 块循环并在每个单词上运行算法,然后使用 += 和末尾的空格 + ' ' 重新组合它们

    将这些东西合并到您现有的代码中,如下所示(使用 cmets):

    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用空格将它们连接起来:

    # 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 之外的大多数其他语言中找到的.

    【讨论】:

    • 非常感谢您帮助我。这行得通,我现在明白了,因为你解释的方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-13
    • 2019-03-25
    • 2016-05-26
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多