1

我正在探索结构。每个结构只有两个值:产品 ID 和数量。例如:

prodcode = 2473 , quantity = 1
prodcode = 2473 , quantity = 4
prodcode = 3328 , quantity = 6
prodcode = 2958 , quantity = 3
prodcode = 2473 , quantity = 7
prodcode = 2958 , quantity = 2
prodcode = 2473 , quantity = -1

我想得到这样的结构的数量总和:

prodcode = 2473 , quantity = 11
prodcode = 3328 , quantity = 6
prodcode = 2958 , quantity = 5

按数量降序排序将是一个加号。这是我用来创建有问题的结构数组的代码:

class Figs < Struct.new(:prodcode, :quantity)  
  def print_csv_record  
    prodcode.length==0 ? printf(",") : printf(prodcode)  
    quantity.length==0 ? printf(",") : printf(",", quantity.to_i)  
    printf("\n")  
  end  
end  

...  

for x in 0...global.length  
  p = Figs.new  
  p.prodcode = global[x][0]  
  p.quantity = global[x][1].to_i  
  figures.push(p)  
end

结构数组是“数字”,但我得到

undefined local variable or method 'quantity' for main:Object (NameError)
4

3 回答 3

0

您可以使用哈希来聚合新结构中的数量:

MyStruct = Struct.new(:prodcode, :quantity)

struct_array.inject({}) do |m, s| 
  m[s.prodcode] ||= MyStruct.new(s.prodcode, 0)
  m[s.prodcode].quantity += quantity
  m
end.values
于 2013-04-03T21:09:54.050 回答
0

比 PinnyM 的答案更冗长,但无论如何,这里有一个相同的建议。:-D

Product = Struct.new(:code, :quantity)

a = Product.new(100, 1)
b = Product.new(100, 3)
c = Product.new(100, 1)

d = Product.new(200, 2)
e = Product.new(200, 2)

products = [a, b, c, d, e] # start
results = {}               # for temporary counting
product_sums = []          # for creating the end structs

products.each do |product|
 results[product.code] ||= 0
 results[product.code] += product.quantity
end

p results
# => {100=>5, 200=>4}

results.each do |code, quantity|
  product_sums << Product.new(code, quantity)
end

p product_sums
# => [#<struct Product code=100, quantity=5>, #<struct Product code=200, quantity=4>]
于 2013-04-03T21:17:31.297 回答
0

Enumerable#group_byEnumerable#reduce让您非常简单地做到这一点:

编辑:使用 OP 的类名,按降序添加排序和更清晰的 print_csv 方法

require 'csv'

class Figs < Struct.new(:prodcode, :quantity)
  def print_csv_record
    print to_a.to_csv
  end
end

a = [Figs[2473,1], Figs[2473,4], Figs[3328,6], Figs[2958,3],
     Figs[2473,7], Figs[2958,2], Figs[2473,-1]]

a.group_by(&:prodcode).
  map { |k,v| Figs[ k, v.map(&:quantity).reduce(:+) ] }.
  sort_by { |e| -e.quantity }

=> [#<struct Figs prodcode=2473, quantity=11>,
    #<struct Figs prodcode=3328, quantity=6>,
    #<struct Figs prodcode=2958, quantity=5>]
于 2013-04-03T22:40:04.940 回答