使用shove将字符串添加到数组,仍然获得空数组

时间:2014-03-27 23:53:53

标签: ruby arrays string rspec

进行猪拉丁挑​​战。我正在尝试使用shove将字符串添加到数组中。我正试图让这个工作s = 'apple'。我希望它在元音中找到'a',添加'ay'使其成为'appleay',并将其推入pig_latin,然后返回pig_latin。

def translate(s)
  vowels = ['a', 'e', 'i', 'o', 'u']
  words = []
  pig_latin = []
  words << s.downcase.split
  for word in words do 
    if vowels.include?(word[0])
      word << 'ay'
      pig_latin << word
    end
  end
  pig_latin
end

当我运行rspec测试时:

require "pig_latin"
describe "#translate" do
  it "translates a word beginning with a vowel" do
    s = translate("apple")
    s.should == "appleay"
  end

我明白了:

#translate
  translates a word beginning with a vowel (FAILED - 1)

Failures:

  1) #translate translates a word beginning with a vowel
     Failure/Error: s.should == "appleay"
       expected: "appleay"
            got: [] (using ==)
     # ./04_pig_latin/pig_latin_spec.rb:26:in `block (2 levels) in <top (required)>'

Finished in 0.00064 seconds
1 example, 1 failure

Failed examples:

rspec ./04_pig_latin/pig_latin_spec.rb:24 # #translate translates a word beginning with a vowel

我的代码出了什么问题?为什么这会返回一个空数组?

1 个答案:

答案 0 :(得分:0)

解决方案:

您需要更改:

words = []
words << s.downcase.split

到此:

words = s.downcase.split

说明:

String.split()会返回一个数组,因此您需要分配给words变量,而不是将其推送到数组中。在原文中,您将一个单词数组嵌入到一个数组中,使words变量看起来像这样:

[["apple"]]