0

我有一个包含多个条目的文本文件。格式是固定的,是name_version_versionNumber.

**example.txt**
cool_name_A_001
something_else_WIP_002
something_else_001
cool_name_B_002
other_thing_010
other_thing_006

退货清单应消除 WIP 条目,并提供最新(最高数量)版本。上面文本文件的输出应该是

cool_name_A_001
cool_name_B_002
other_thing_010
something_else_001

到目前为止,我有

#import files
x = File.readlines("path to txt file").delete_if {|x| x.scan(/[WIP]../).include? "WIP"}.sort

#include latest copy only
#include latest copy only
def latest_version(x)
list = []
i = 0
while i<x.length
    if list.map {|x| x.scan(/\D+/)}.flatten.include? x[i].scan(/\D+/)
        zet = list.map {|x| x.scan(/\D+/)}.flatten.rindex x[i].scan(/\D+/)
        if list[zet].scan(/\d+/) > x[i].scan(/\d+/)
            i+=1
        else 
            list[zet] = x[i]
            i+=1
        end
    elsif x[i].scan(/\D+/) == x[i+1].scan(/\D+/)
        if x[i].scan(/\d+/) > x[i+1].scan(/\d+/)
            list << x[i]
            i+=1
        else
            list << x[i+1]
            i+=1
        end
    else
        list << x[i]
        i+=1
    end
  end
  list
end

puts latest_version(x)

我收到以下错误

rb:10:in `latest_version': private method `scan' called for 114:Fixnum (NoMethodError)

error 方法在 irb 中有效,无法弄清楚为什么会出错?此外,无法判断逻辑是否实现了预期的结果。请帮忙!谢谢 :)

1.9.3p374 :098 > y
 => ["something_SA_R33\n", "whatever_SA_R012\n", "anything_SB_R012\n"]
1.9.3p374 :099 > y.map {|x| x.scan(/\d+/)}.flatten
 => ["33", "012", "012"]  
4

3 回答 3

1

以相反的顺序对它们进行排序,然后遍历所有元素,删除所有 WIP 元素并保存每个组中的第一个(匹配 ^/(.*?)_\d{3}$/)不是更容易吗? 所有这些扫描看起来都很脆弱。

于 2013-03-13T21:30:54.540 回答
0

非常值得怀疑的是真的需要创建如此复杂的方法。Ruby 有很多方法可以让生活更轻松。

So, your one of your mistakes is to use same names for method argument latest_version(x) and for map iteration list.map{|x| ... }. It is not very good practice

于 2013-03-13T21:38:53.203 回答
0

I'd use something like:

data = %w[
  cool_name_A_001
  something_else_WIP_002
  something_else_001
  cool_name_B_002
  other_thing_010
  other_thing_006
]

data.reject{ |s| s['_WIP_'] }.group_by{ |s| s[/\A(.+)_\d+/, 1] }.map{ |k, v| v.max }.sort
[
    [0] "cool_name_A_001",
    [1] "cool_name_B_002",
    [2] "other_thing_010",
    [3] "something_else_001"
]

To read from a file replace data with x = File.readlines("path to txt file").

But that's just me.

于 2013-03-13T21:56:19.600 回答