【问题标题】:Does Instance Variables of a module shared between class with the mixin?模块的实例变量是否在类之间与 mixin 共享?
【发布时间】:2012-03-13 17:35:05
【问题描述】:

我想知道 Ruby 模块的实例变量如何在多个“混合”它的类中表现。我写了一个示例代码来测试它:

# Here is a module I created with one instance variable and two instance methods.
module SharedVar
  @color = 'red'
  def change_color(new_color)
    @color = new_color
  end
  def show_color
    puts @color
  end
end

class Example1
  include SharedVar
  def initialize(name)
    @name     = name
  end
end

class Example2
  include SharedVar
  def initialize(name)
    @name     = name
  end
end

ex1 = Example1.new("Bicylops")
ex2 = Example2.new("Cool")

# There is neither output or complains about the following method call.
ex1.show_color
ex1.change_color('black')
ex2.show_color

为什么它不起作用?有人可以解释@color 在多个Example$ 实例中的实际行为吗?

【问题讨论】:

    标签: ruby variables scope instance mixins


    【解决方案1】:

    在 Ruby 中,模块和类都是对象,因此可以为它们设置实例变量。

    module Test
      @test = 'red'
      def self.print_test
        puts @test
      end
    end
    
    Test.print_test #=> red
    

    你的错误是认为变量@color 是相同的:

    module SharedVar
      @color
    end
    

    module SharedVar
      def show_color
        @color
      end
    end
    

    这不是。

    在第一个示例中,实例变量属于 SharedVar 对象,在第二个示例中,实例变量属于包含模块的对象。

    self 指针的另一种解释。在第一个示例中,self 指针设置为模块对象SharedVar,因此键入@color 将引用对象SharedVar,并且与另一个对象没有任何联系。在第二个示例中,show_color 方法只能在某些对象上调用,即ex1.show_color,因此 self 指针将指向 ex1 对象。所以在这种情况下,实例变量将引用ex1 对象。

    【讨论】:

    • 解释得很清楚!所以如果我设计的模块是为了与其他类混合。我应该在instance method 中定义instance variable,我的理解正确吗?
    • 是的,只要计算一下当前的self是什么,然后你就可以知道实例变量将被放置在哪里。
    • 谢谢。我目前只是在学习 Ruby,而不是 current self 部分。似乎比javaScript 更优雅的语言。
    【解决方案2】:

    你已经在一个类中包含了一个模块......所以实例变量@color应该是类Example1和Example2的实例变量

    所以如果你想访问 @color 变量意味着你想创建一个类的对象然后你可以访问它

    前任

    irb(main):028:0> ex1.change_color('black')
    => "black"
    irb(main):029:0> ex1.show_color
    black
    irb(main):031:0> ex2.change_color('red')
    => "red"
    irb(main):032:0> ex2.show_color
    red
    

    【讨论】:

    • 这正是我正在做的。但是ex1ex2 都没有定义color
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-19
    • 1970-01-01
    • 2011-04-14
    • 1970-01-01
    相关资源
    最近更新 更多