为什么我们需要为课程要求并包含一个模块?

时间:2013-10-28 13:53:44

标签: ruby

当我已经使用"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

3 个答案:

答案 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

如果您的模块是在单独的文件中定义的,则必须使用requirerequire_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