有没有更干净的方法来写这个?我不喜欢代码重复。
# Adds the content of two arrays except the first cell because the first cell is a string
# The arrays don't have to be the same length.
# * *Args* :
# - +a+ -> first array
# - +b+ -> second array
#
def add_array(a,b)
if a.size >= b.size then
a.map.with_index{ |m,i|if i != 0 then m + b[i].to_i else m end}
else
b.map.with_index{ |m,i|if i != 0 then m + a[i].to_i else m end}
end
end
输入示例:
arr1 = ["foo",1,2,3,4,5]
arr2 = []
arr3 = ["foo",2,4,6,5,7,8,9,4,5,6]
arr2 = add_array(arr1, arr2)
puts arr2.inspect
arr2 = add_array(arr2, arr3)
puts arr2.inspect
输出 :
["foo", 1, 2 ,3 ,4 ,5]
["foo", 3, 6, 9, 9, 12, 8, 9, 4, 5, 6]
随意评论/批评并表达您的想象力!
谢谢。