我试图创建一个接受数组并将其内容转换为字符串句子的函数。
def sentence_maker(array)
clone = array # making a copy of array
array = array.drop(1) # dropping the first element
array = array.unshift(clone[0].capitalize) # inserting a capitalized version of the first element of the clone
array.each do |element|
print element.to_s + ' ' # a space after each word
end
array = array.unshift # remove the space at the end of the last word
array = array << '.' # inserting a period at the end of the array
end
sentence_maker(['i', 'am', 'awesome'])
我的rspec回归:
expected: "All my socks are dirty."
got: ["All", "my", "socks", "are", "dirty", "."]
答案 0 :(得分:3)
您正在each
循环中打印数组的元素,但您没有创建/返回新的String
。
清洁方法如下:
array = ['i', 'am', 'awesome']
array[0] = array[0].capitalize
array.join(" ").concat(".") # => "I am awesome."