进行猪拉丁挑战。我正在尝试使用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
我的代码出了什么问题?为什么这会返回一个空数组?
答案 0 :(得分:0)
您需要更改:
words = []
words << s.downcase.split
到此:
words = s.downcase.split
String.split()
会返回一个数组,因此您需要将分配给words
变量,而不是将其推送到数组中。在原文中,您将一个单词数组嵌入到一个数组中,使words
变量看起来像这样:
[["apple"]]