I’m new to Ruby and as part of my studies I got a task to convert 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_byto sort the list however you want.So in your code, you have the array
newproduct, so just do this:If you want to sort by price: