2013-08-19 80 views
0

有没有更清晰的方式来写这个?我不喜欢那个代码重复。删除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] 

随意评论/批评,表达你的想象!

谢谢。

+1

给出一个示例输入和输出,可能是我们可以给出比你更好的代码.. –

+0

@Babai例子添加。 – Pol0nium

回答

1

第一步:

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 
    add_array(b, a) 
    end 
end 
+0

是的,很明显,但我没有考虑它。谢谢。 – Pol0nium

2

随着愚见新手意见;

def add_array(a,b) 
    a, b = b, a if b.size > a.size 
    a.map.with_index{ |m,i|if i != 0 then m + b[i].to_i else m end} 
end 

编辑:Pol的建议是更好的。

+0

我总是被告知三元条件是一个坏习惯,因为他们很难理解某个没有编写代码并且不得不对其进行修改的人。你怎么看? (无论如何,我喜欢你的解决方案;)) – Pol0nium

+1

我不认为他们总是不好,但在这里你可以交换这样的行:a,b = b,a如果b.size> a.size – iCanLearn

+0

谢谢分享你的意见 – Pol0nium

1
def add_array(a,b) 
    a.map.with_index { |m, i| i.zero? && m || m + choose(a, b)[i].to_i } 
end 

def choose(a, b) 
    if a.size > b.size 
    b 
    else 
    a 
    end 
end 

根据大小拉取数组的顺序意味着您可以在其他地方使用它。

去除if消极是我努力的方向。

所有的样本数据都是整数,但我把强制转化为整数。

1
def add_array(a,b) 
    a.size > b.size ? merge_arrays(a,b) : merge_arrays(b,a) 
end 

def merge_arrays(a,b) 
a.map.with_index{ |m,i|if i != 0 then m + b[i].to_i else m end} 
end 

在这种情况下,数组大小的检查只进行一次。我介绍了这个新功能,以确保它更具可读性。