为什么结束时期不会出现?

时间:2022-06-17 21:28:49

I'm trying to make a function that takes an array and turns its contents into a string sentence.

我正在尝试创建一个函数,它接受一个数组并将其内容转换为字符串句子。

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'])

My rspec returns:

我的rspec返回:

expected: "All my socks are dirty."
            got: ["All", "my", "socks", "are", "dirty", "."]

1 个解决方案

#1


3  

You are printing the elements of the array in the each loop but you are not creating/returning a new String.

您正在每个循环中打印数组的元素,但您没有创建/返回新的String。

A cleaner approach is below:

更清洁的方法如下:

array = ['i', 'am', 'awesome']
array[0] = array[0].capitalize
array.join(" ").concat(".") # => "I am awesome."

#1


3  

You are printing the elements of the array in the each loop but you are not creating/returning a new String.

您正在每个循环中打印数组的元素,但您没有创建/返回新的String。

A cleaner approach is below:

更清洁的方法如下:

array = ['i', 'am', 'awesome']
array[0] = array[0].capitalize
array.join(" ").concat(".") # => "I am awesome."