如何包含模块的常量和变量?

时间:2010-07-29 00:35:01

标签: ruby

我有一个具有常量和变量的模块。

我想知道如何在课堂上加入这些内容?

module Software
  VAR = 'hejsan'

  def exit
    @text = "exited"
    puts @text
  end
end

class Windows
  extend Software
  def self.start
    exit
    puts VAR
    puts @text
  end
end

Windows.start

这可能吗?

2 个答案:

答案 0 :(得分:9)

Ruby 1.9.3:

module Software
  VAR = 'hejsan'

  module ClassMethods
    def exit
      @text = "exited"
      puts @text
    end
  end

  module InstanceMethods

  end

  def self.included(receiver)
    receiver.extend         ClassMethods
    receiver.send :include, InstanceMethods
  end
end

class Windows
  include Software
  def self.start
    exit
    puts VAR
    puts @text
  end
end

Windows.start

在IRB:

exited
hejsan
exited

答案 1 :(得分:3)

无法完全按照自己的意愿行事。实例变量严格按每个对象。

这恰好符合您的期望,但@text设置为Windows而不是Software

module Software
  VAR = 'hejsan'

  def exit
    @text = "exited"
    puts @text
  end
end

class Windows
  class <<self
    include Software
    def start
      exit
      puts VAR
      puts @text
    end
  end
end

Windows.start