【发布时间】:2018-09-30 15:10:09
【问题描述】:
我对使用“include”与“extend”感到困惑,在搜索了几个小时后,我得到的只是模块方法与包括模块在内的类的实例一起使用,以及在类扩展时与类本身一起使用的模块方法这些方法的模块。
但这并没有帮助我弄清楚,为什么在注释“#extend Inventoryable”中的扩展模块行时这段代码会出错 在取消注释时工作,这是代码
module Inventoryable
def create(attributes)
object = new(attributes)
instances.push(object)
return object
end
def instances
@instances ||= []
end
def stock_count
@stock_count ||= 0
end
def stock_count=(number)
@stock_count = number
end
def in_stock?
stock_count > 0
end
end
class Shirt
#extend Inventoryable
include Inventoryable
attr_accessor :attributes
def initialize(attributes)
@attributes = attributes
end
end
shirt1 = Shirt.create(name: "MTF", size: "L")
shirt2 = Shirt.create(name: "MTF", size: "M")
puts Shirt.instances.inspect
输出是
store2.rb:52:in `<main>': undefined method `create' for Shirt:Class (NoMethodError)
当取消注释“扩展 Inventoryable”以使代码工作时:
module Inventoryable
def create(attributes)
object = new(attributes)
instances.push(object)
return object
end
def instances
@instances ||= []
end
def stock_count
@stock_count ||= 0
end
def stock_count=(number)
@stock_count = number
end
def in_stock?
stock_count > 0
end
end
class Shirt
extend Inventoryable
include Inventoryable
attr_accessor :attributes
def initialize(attributes)
@attributes = attributes
end
end
shirt1 = Shirt.create(name: "MTF", size: "L")
shirt2 = Shirt.create(name: "MTF", size: "M")
puts Shirt.instances.inspect
使代码工作并输出以下内容
[#<Shirt:0x0055792cb93890 @attributes={:name=>"MTF", :size=>"L"}>, #<Shirt:0x0055792cb937a0 @attributes={:name=>"MTF", :size=>"M"}>]
这有点令人困惑,但我只需要知道,为什么我需要扩展模块以避免错误?以及如何编辑此代码以使其在没有扩展方法的情况下工作? ,代码中还剩下什么依赖于扩展?
【问题讨论】:
标签: ruby-on-rails ruby include extend