Ich habe eine Klasse Store, jeder Store hat einen Hash mit verschiedenen Produkten und jedes Produkt hat einen Hash mit verschiedenen Arten von Verkauf.Ruby sort_by von Objekten/Klassen undefined Methode 'sort_by' für
class Store
def initialize
@store_products = Hash.new
#@store_products['product_id'] = Product
end
end
class Product < Store
def initialize(model)
@model = model
@sell_option = Hash.new
#@sell_option['sell_name'] = SellOption
end
end
class SellOption < Product
def initialize(size, price, stock)
@size = size
@price = price
@stock = stock
end
end
Mit diesen Daten:
product1 = Product.new("shirt1")
product1.add_sell_option(SellOption.new("S", 12, 10))
product1.add_sell_option(SellOption.new("M", 15, 10))
product1.add_sell_option(SellOption.new("L", 14, 10))
product2 = Product.new("shirt2")
product2.add_sell_option(SellOption.new("M", 6, 10))
product2.add_sell_option(SellOption.new("L", 7, 10))
product3 = Product.new("shirt2")
product3.add_sell_option(SellOption.new("M", 10, 10))
product3.add_sell_option(SellOption.new("L", 11, 10))
store = Store.new
store.add(product1)
store.add(product2)
store.add(product3)
In der Klasse Shop möchte ich eine Methode tun, die nach Preis meine Produkte sortieren. Wenn die Verwendung dieser Ausdruck:
puts store.products_sorted_by_price
def products_sorted_by_price
@store_products.each_value do |product|
product.sort_by{|k, v| v.value.price}
end
end
Warum es gibt "nicht definierte Methode 'sort_by' für Produkt ..." !!
Erben; weil ich mehr Methoden habe, die benötigt werden. Von verschiedenen Preisen habe ich eine Methode, die den Mindestpreis wählen. Und mein Fehler war, dass ich den Auftrag nicht auf das Produkt anwendete, sondern nur auf einen von ihnen. – Rat