Ruby on rails 类范围常数

Ruby on rails 类范围常数,ruby-on-rails,scope,constants,Ruby On Rails,Scope,Constants,我需要为一个模型实现操作符 代码如下所示: class Product < ActiveRecord::Base sizes_map = ["s", "m", "l", "xl", "xxl"] def < (rhs) return sizes_map.index(self.size_label) < sizes_map.index(rhs.size_label) end end 类产品

我需要为一个模型实现操作符

代码如下所示:

class Product < ActiveRecord::Base
    sizes_map = ["s", "m", "l", "xl", "xxl"]

    def < (rhs)
        return sizes_map.index(self.size_label) < sizes_map.index(rhs.size_label)
    end
end
类产品
当我这样做时:

pl = Product.new :size_label => "s"
pr = Product.new :size_label => "l"
pl < pr
pl=Product.new:size\u label=>“s”
pr=产品。新:尺寸\标签=>“l”
pl
我发现以下错误:

NameError:未定义的局部变量或方法“sizes\u map”

事实证明,这个类范围的常量在它的方法中是不可见的

此外,Product:size\u map也会引发相同的错误


这里出了什么问题?

size\u map
应该是一个常量,如果您希望以这种方式在类中默认它。常量以大写形式定义

class Product < ActiveRecord::Base
  SIZES = ["s", "m", "l", "xl", "xxl"]

  def <(rhs)
    SIZES.index(size_label) < SIZES.index(rhs.size_label)
  end
end
类产品如果希望在类中以这种方式默认def
大小\u map
应该是一个常量。常量以大写形式定义

class Product < ActiveRecord::Base
  SIZES = ["s", "m", "l", "xl", "xxl"]

  def <(rhs)
    SIZES.index(size_label) < SIZES.index(rhs.size_label)
  end
end
类产品def啊,我忘了大写。谢谢谢谢你的补充。顺便说一句,这些编码约定列在哪里?啊,我忘了大写。谢谢谢谢你的补充。顺便问一下,这些编码约定在哪里列出?