未定义对象/类的Ruby排序方法&x27;按'排序;对于
我有一个类商店,每个商店都有一个包含不同产品的散列,每个产品都有一个包含不同种类销售的散列未定义对象/类的Ruby排序方法&x27;按'排序;对于,ruby,sorting,hash,Ruby,Sorting,Hash,我有一个类商店,每个商店都有一个包含不同产品的散列,每个产品都有一个包含不同种类销售的散列 class Store def initialize @store_products = Hash.new #@store_products['product_id'] = Product end end class Product < Store def initialize(model) @model = model
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
在class Store中,我想用一种方法按价格对我的产品进行排序。
如果使用此表达式:
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
为什么它会为产品返回“未定义的方法”sort_by 关于你的问题,我有很多不明白的地方: -为什么
产品
继承自存储
?
-为什么SellOption
继承自Product
?
-你想按价格对产品进行分类吗?
-如果卖出期权有不同的价格,你会使用哪个价格?
-为什么不同的尺寸有不同的价格?
-您从v
中提取的值是什么,它应该是产品
无论如何。。。sort_by通常在可枚举的
上运行,就我所见,产品
不是一个。因此,准确的答案是Ruby对Product
说未定义的方法“sort\u by”,因为您没有在Product
上定义sort\u by
,也没有从定义它的类继承
我猜你是想做更像这样的事情:
@store_products.sort_by {|k,v| v.value.price }?
除此之外,我不知道什么是值
,在你真正完成排序之前,你必须弄清楚如何处理产品中的多个价格,但希望这能为你指明正确的方向
澄清你的问题,我可以尝试改进答案。Inherits;因为我有更多需要的方法。从不同的价格中,我有一个选择最小价格的方法。我的错误是,我没有将订单应用于产品,而是仅应用于其中一个产品。
@store_products.sort_by {|k,v| v.value.price }?