我是Ruby的新手,作为学习的一部分,我得到了一个任务,将CSV文件转换为我可以按价格等进行排序的任务。但是,我无法创建对象列表。我知道我可以制作object1,object2等,但我不知道如何自动执行此操作。Ruby:将一个CSV列表转换为单独的对象
这是我到目前为止的代码:
class Product
attr_reader :id, :name, :price, :stock
def initialize(id,name,price,stock)
@id = id
@name=name
@price=price
@stock=stock
end
def readout(variable)
print product.id
print "|"
print product.name
print "|"
print product.price
print "|"
print product.stock
puts ""
end
end
products = []
newproducts= []
File.open("products.csv" , "r") do |f|
f.each_line do |line|
products << line
end
end
puts products
products.each do |product|
data = product.split(",")
inbetween = Product.new(data[0].to_s, data[1].to_s, data[2].to_i, data[3].to_i)
inbetween
newproducts << inbetween
end
newproducts.sort_by{|x| x.price}
newproducts.each do |product|
print product.id
print "|"
print product.name
print "|"
print product.price
print "|"
print product.stock
puts ""
end
你应该看看FasterCSV的宝石。做product.split(“,”)不会处理嵌入式逗号等内容。 FasterCSV将处理更广泛的输入。否则,我会采取非常类似的方法来处理你已经在做的事情。 – 2010-11-18 23:03:09
恐怕我的学校想要我们写这样的东西开始。 – Fallion 2010-11-19 18:29:53