将第一个数组的每个元素添加到第二个数组的每个元素

时间:2017-06-09 13:06:44

标签: arrays ruby

我想根据两个第一和第二名数组创建一些可以创建100个名字的人。

first_name = ['Tom', 'John', 'Allan', 'Steven', 'Robert', 'Lucy','Ruth', 'Anna', 'Edith', 'Jessica']
second_name = ['Ross', 'Smith', 'Jones', "Wells", "Bain", "Gillespie", "Sutton", "Pearce", "Johnstone", "Lightbody"]

我希望循环显示名字,添加每个第二个名字,然后再转到第二个first_name

我尝试使用映射方法,但收到了错误消息。

2 个答案:

答案 0 :(得分:2)

你可以......

first_name.zip(second_name).map{|n|n.join(' ')}

Zip会创建一系列数组:[[' Tom',' Ross'],[' John'' Smith'] ...]

每个元素的加入会将[' Tom',' Ross']更改为“Tom Ross'

如果你想通过更传统的循环使用each_with_index并使用第一个数组中元素的索引来查找第二个数组中相应的姓氏。

result = []
first_name.each_with_index do |name, i|
  result << "#{name} #{last_name[i]}"
end

答案 1 :(得分:0)

你走了:

select c.ChainIdentifier, s.SupplierIdentifier, s.SupplierName, we.Weekend, 

sum(sales_units_cy) as TY_unitSales, sum(sales_cost_cy) as TY_costDollars, sum(sales_units_ret_cy) as TY_retailDollars,

sum(sales_units_ly) as LY_unitSales, sum(sales_cost_ly) as LY_costDollars, sum(sales_units_ret_ly) as LY_retailDollars

from ir_sales_summary i

left join Chains c
on c.ChainID = i.ChainID

inner join Suppliers s
on s.SupplierID = i.SupplierID

inner join tmpWeekend we
on we.SaleDate = i.saledate

where year(i.saledate) = '2017'

group by c.ChainIdentifier, s.SupplierIdentifier, s.SupplierName, we.Weekend