简体   繁体   English

Ruby - 循环遍历一个数组,删除该数组的结束元素和 append 到另一个数组

[英]Ruby - Loop through an array , Remove end element of that array and append it to another array

I am attempting the following coding challenge.我正在尝试以下编码挑战。

Write a program to loop through the array named food and remove the end element of that array, and append it to the array named drink .编写一个程序循环遍历名为food的数组并删除该数组的末尾元素,并将 append 传递给名为drink的数组。 The initial values of these arrays are:这些 arrays 的初始值为:

food = ["Tempura", "Prawn", "Squid", "Fish", "Chips"]
drink = ["Kombucha", "Coconut Mango", "Allberry", "Yogurt Rice", "Milk bubble tea"]

I know how to get the last element from the first array and append it to the second array.我知道如何从第一个数组和 append 获取最后一个元素到第二个数组。

print drink << food.slice(-1)

I struggle with finding the loop so that I can get the following out.我很难找到循环,以便我可以得到以下内容。

food_&_drink = ["Kombucha", "Coconut Mango", "Allberry", "Yogurt Rice", "Milk bubble tea", "Chips", "Fish", "Squid", "Prawn", "Tempura"]

How to match element 1 from the food array to element 4 in the drink array.如何将食物数组中的元素 1 与饮料数组中的元素 4 匹配。 With the method that I know, I am not getting the output the want:使用我知道的方法,我没有得到想要的 output:

print food.flatten.zip(drink)

The simplest/clearest solution to reach your desired output (nondestructively):达到您想要的 output(非破坏性)的最简单/最清晰的解决方案:

drink + food.reverse

The solution matching your wording:与您的措辞相匹配的解决方案:

until food.empty?
  drink << food.pop
end

or even甚至

drink << food.pop until food.empty?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM