我有两个数组:
a = [50, 17, 54, 26]
b = [19, 7, 8, 18, 36, 8, 18, 36, 18, 14]
我想在b
的元素中添加a
的相应元素。当a
的元素用完时,我想循环通过a
来提供元素。结果应该是:
c = [69, 24, 62, 44, 86, 25, 72, 62, 68, 31]
我怎么能这样做?
答案 0 :(得分:4)
b.zip(a * (b.size / a.size + 1)).map { |o| o.reduce(:+) }
#⇒ [69, 24, 62, 44, 86, 25, 72, 62, 68, 31]
或者,@ SimpleLime更好更简洁:
b.zip(a.cycle).map(&:sum)
答案 1 :(得分:4)
a = [50, 17, 54, 26]
b = [19, 7, 8, 18, 36, 8, 18, 36, 18, 14]
enum = a.cycle
b.map { |e| e + enum.next }
#=> [69, 24, 62, 44, 86, 25, 72, 62, 68, 31]
答案 2 :(得分:1)
另一个,使用map
,with_index
和模数:
b.map.with_index { |e, i| e + a[i % a.size] }
#=> [69, 24, 62, 44, 86, 25, 72, 62, 68, 31]
答案 3 :(得分:-1)
编辑:仅适用于rails
def add_arrays(array_a, array_b)
results = []
array_b.in_groups_of(4).each do |group|
group.each_with_index do |record, j|
results << (record + array_a[j])
end
end
results
end
没有测试过,但应该这样做