【问题标题】:Removing code duplication in ruby删除 ruby​​ 中的代码重复
【发布时间】:2013-08-19 14:11:35
【问题描述】:

有没有更简洁的方法来写这个?我不喜欢代码重复。

# 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 示例已添加。

标签: ruby coding-style


【解决方案1】:

以我谦虚的新手意见;

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

编辑:钋的建议更好。

【讨论】:

  • 我一直被告知三元条件是一个坏习惯,因为对于那些没有编写代码并且必须修改它的人来说,它们很难理解。你怎么看? (无论如何,我喜欢你的解决方案;))
  • 我不认为它们总是坏的,但在这里你可以用类似的东西交换那行:a,b = b,a if b.size > a.size
  • 感谢您分享您的意见
【解决方案2】:

第一步:

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

【讨论】:

  • 是的,很明显,但我没想到。谢谢。
【解决方案3】:
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 否定是我努力的目标。

所有样本数据都已经是整数了,但我将强制转换为整数。

【讨论】:

    【解决方案4】:
    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
    

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

    【讨论】:

      猜你喜欢
      • 2011-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-19
      • 1970-01-01
      相关资源
      最近更新 更多