开发者

Ruby: Turning a CSV list into seperate objects

I'm new to Ruby and as part of my studies I got a task to con开发者_如何学编程vert a CSV file into something I can sort by price and such. However I am having trouble creating a list of objects. I know that I could make object1, object2 and such, but I do not know how to do this automatically.

This is the code I have so far:

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


Probably the easiest thing to do is to create a list and then, when you create each new product, you just push it onto the list. Then you can use sort_by to sort the list however you want.

So in your code, you have the array newproduct, so just do this:

products.each do |product|
  data = product.split(",")
  newproduct.push(Products.new(data[0], data[1], data[2], data[3]))
end

If you want to sort by price:

newproduct.sort_by{|x| x.price}


There are of course many ways to solve the task you have been given and I don't think you are so far from a workable solution. If you just make sure that you actually save the Products class when you create it, you have a list you can work with.

newproducts << Product.new(data[0], data[1], data[2], data[3])

As you may notice, I made a little adjustment to your syntax. I changed the class Products to Product since it only keeps track of one product. Then I also changed the array name from newproduct to newproducts since that is actually where the different products will be stored.

After that, you have an array object which you can perform your sort_by tasks with.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜