当我已经使用"stacklike"
的include方法时,为什么我需要在stack.rb
中要求stacklike.rb
?如果我删除require
,则会产生错误"Uninitialized constant Stack::Stacklike (NameError)"
。
stacklike.rb
module Stacklike
def stack
@stack ||= [] #@stack || @stack = []
end
def add_to_stack(obj)
stack.push(obj)
end
def take_from_stack
stack.pop
end
end
stack.rb
require_relative "stacklike"
class Stack
include Stacklike
end
s = Stack.new
s.add_to_stack("people")
s.add_to_stack("people2")
s.add_to_stack("people3")
puts "obj currently on the stack:"
puts s.stack
taken = s.take_from_stack
puts "Removed this stack:"
puts taken
puts "Now on stack:"
puts s.stack
答案 0 :(得分:0)
我们使用Module#include
方法将模块名称作为该方法的参数,在需求类的祖先链中添加这些模块。现在Kernel#require_relative
将提供从需求文件到顶层所需文件的类,模块等。
当您执行require_relative "stacklike"
时,它意味着您在文件stacklike.rb
中定义的模块,类等等现在可用于文件的顶级{{1} }。现在要使用模块stack.rb
的实例方法,使用类Stacklike
的实例,您需要将该模块包含在类Stack
中。
答案 1 :(得分:0)
Ruby的include
不访问文件系统。必须已定义给定模块或将引发NameError
:
# foo.rb
class Foo
include Bar # NameError: uninitialized constant Foo::Bar
end
这适用(一个文件中的所有内容):
# foo.rb
module Bar
end
class Foo
include Bar
end
如果您的模块是在单独的文件中定义的,则必须使用require
或require_relative
加载此文件:
# bar.rb
module Bar
end
# foo.rb
require_relative 'bar'
class Foo
include Bar
end
答案 2 :(得分:0)
require
是关于文件的。 include
是关于模块的。由于模块和文件在Ruby中并不一一对应,因此需要文件和包含模块是不同的任务。它们需要单独控制。
模块Stacklike
的内容写在文件stacklike.rb
上,因此您需要该文件才能访问该模块。然后,如果您愿意,则需要包含Stack
。