Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
未定义对象/类的Ruby排序方法&x27;按'排序;对于_Ruby_Sorting_Hash - Fatal编程技术网

未定义对象/类的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 }?