有沒有更清晰的方式來寫這個?我不喜歡那個代碼重複。刪除ruby中的代碼重複
# 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]
隨意評論/批評,表達你的想象!
謝謝。
給出一個示例輸入和輸出,可能是我們可以給出比你更好的代碼.. –
@Babai例子添加。 – Pol0nium