Ruby:Pig Latin:迭代多个单词的方法(不工作)

pet*_*ete 2 ruby

对不起,关于TestFirst.org Ruby练习的另一个问题是编写一个来自新手的'Pig Latin'方法.其他答案有所帮助,但我无法成功地适应它们.主要问题是我正在尝试编写一种方法来扫描一串单词(不只是一个单词),修改一些单词(如果适用),然后返回完整的字符串.

下面是我的代码尝试执行练习的第一部分,即将"ay"附加到以元音开头的任何单词.但是,它对我不起作用 - 似乎是.include?从与单个字母(?)比较时永远不会返回true

任何帮助深表感谢!

# PIG LATIN
# If any word within the input string begins with a vowel, add an "ay" to the end of the word

def translate(string)

  vowels_array = %w{a e i o u y}
  consonants_array = ('a'..'z').to_a - vowels_array

  string_array = string.split

  string_array.each do |word|
    if vowels_array.include?(word[0])
      word + 'ay'
    end
  end

  return string_array.join(" ")

end 

translate("apple orange mango")    # => "appleay orangeay mango" but does not
Run Code Online (Sandbox Code Playgroud)

mde*_*tis 5

string_array.each只是迭代string_array,不改变它; 为了更新数组的内容,你应该使用map!:

  # ...
  string_array.map! do |word|
    if vowels_array.include?(word[0])
      word + 'ay'
    else
      word
    end
  end
  # ...

translate("apple orange mango")    #=> "appleay orangeay mango"
Run Code Online (Sandbox Code Playgroud)

目的else word end是在if不满足条件时也返回单词.


从数组操作的角度来看,在大多数情况下,操作字符串的最佳方法是regexp:

def translate(string)
  string.gsub(/(^|\s)[aeiouy]\S*/i, '\0ay')
end

translate("apple orange mango") #=> "appleay orangeay mango"
Run Code Online (Sandbox Code Playgroud)