新手问题 问个超弱的问题:一条代码太长了,维护的时候想换行该怎么换。。。

Catherine · 2015年12月23日 · 最后由 catherine 回复于 2015年12月23日 · 3357 次阅读
sheet1.row(i).push (item.category ? item.category.name : "-"), (item.type ? item.type.name : "-"), item.product_number, item.name, (item.specification ? item.specification.name : "-"), item.wrap_way, item.product_number, (item.specification.human_unit_price/item.specification.value.round(2)).to_s, item.specification.price,item.place, item.description, item.vender ? item.vender.name : "", item.number, item.logo, item.enabled

没看错,这是一条代码。。。

感觉就是这个段代码逻辑复杂,在测试充分的情况下,采用提取方法等重构手法进行拆分;否则即使把代码分成多行,还是很难维护;如果实在要强制换行的话,可以加 \,不过不建议这样弄。类似下面这样:

2.2.0-preview1 :002> a = "hello \
2.2.0-preview1 :002"> world "
 => "hello world "
2.2.0-preview1 :002> a
 => "hello world "

2 楼 已删除

提取出变量,至少看的清楚一些...

三目运算符太多了... 可以试试比如把item.category ? item.category.name : "-"换成item.category.try(:name) || "-"

sheet1.row(i).push (item.category ? item.category.name : "-"),
                   (item.type ? item.type.name : "-"),
                   # ...

跳出来看问题啊

cols = []
cols << item.category.try(:name) || '-'
cols << item.type.try(:name) || '-'
cols << item.product_number
cols << item.name
cols << item.specification.try(:name) || '-'
cols << item.wrap_way
cols << item.product_number
cols << (item.specification.human_unit_price / item.specification.value.round(2)).to_s
cols << item.specification.price,item.place
cols << item.description
cols << item.vender.try(:name) || ''
cols << item.number
cols << item.logo
cols << item.enabled

sheet1.row(i).push(*cols)

这样多清晰啊,修改又方便

谢谢各位回复! #7 楼 @huacnlee 受教了!老是想怎么换行,套进去了,你这样一说清晰太多了!

需要 登录 后方可回复, 如果你还没有账号请 注册新账号