Sortanarraydependingongivensetofcharacterswithineachelement

I have an array made of a number of elements read from a .txt file. Each element is long and has a lot of information, for instance:
20201102066000000000000000000000000020052IC04008409Z8000000000030546676591AFIP

All the lines are already part of the array lines_array, but I need to sort them out depending on the content of the 36° character until the 51°, which in the example provided above would be:
20052IC04008409Z

I was already able to catch the patterns from each of the elements in the array:

    lines_array = File.readlines(complete_filename)

    pattern = nil
    lines_array.each do |line|
    pattern = line[36] + line[37] + line[38] + line[39] + line[40] + line[41] + line[42] + line[43] + 
    line[44] + line[45] + line[46] + line[47] + line[48] + line[49] + line[50] + line[51]
    end

我现在需要做的是能够根据变量 variable 的内容按字母顺序对数组的所有元素(带有长元素)进行排序pattern。我尝试了方法sortsort_by但我无法将我的变量pattern作为参数传递。例如,三个给定元素的正确顺序是:

20201102066000000000000000000000000020001IC04180127X8000000000030546676591AFIP
20201104066000000000000000000000000020001IC04182757T8000000000030546676591AFIP
20201102066000000000000000000000000020001IC05020641D8000000000030546676591AFIP

有什么帮助吗?

回答

首先,有更简单、更简洁的方法来提取您想要的子字符串,您可以使用String#[]or String#slice

# These do the same thing, use whichever reads better to you.
pattern = line[36, 16]
pattern = line.slice(36, 16)
pattern = line[36..51]
pattern = line.slice(36..51)

然后你可以Enumerable#sort_by通过使用一个块来在那个切片上sort_by

sorted = lines_array.sort_by { |str| str[36, 16] }

  • Range version might make more sense to the OP since that is how they described the positioning. e.g. `str[36..51]`

以上是Sortanarraydependingongivensetofcharacterswithineachelement的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>