Ruby,mixin实例变量和方法 [英] Ruby, mixin instance variables and methods

查看:112
本文介绍了Ruby,mixin实例变量和方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个文件,一个文件带有模块ToMix:

I have two files, one with module ToMix:

module ToMix
    @module_var = "modulevar"
    def self.mix_function
        puts "mix_function SELF: #{@module_var}"
    end
    def mix_function
        puts "mix_function: #{@module_var}"
    end     
    class MixClass
        attr_accessor :mixclassvar
        def initialize(value)
            @mixclassvar = value
        end
    end
end

我想混入另一个文件中的类TestInclude

:

which I want to mixin to the class TestInclude in the other file:

class TestInclude
    require "ToMixFile"
    include ToMix
end

有人可以解释为什么未定义实例变量@module_var和方法self.mix_functionmix_function吗?我该如何定义它们?

Could someone explain why the instance variable @module_var and methods self.mix_function, mix_function are undefined? And how would I define them?

t2 = TestInclude.new()
t2.mix_function                           # => error undefined (exected call to mix_function)
t2.module_var = "test set module_var"     # => error undefined
TestInclude.mix_function                  # => error undefined (expected call to self.mix_function)
TestInclude.method_defined? :mix_function # => false

推荐答案

模块向事物添加函数; attr_accessor添加了用于与变量进行交互的功能.

Modules add functions to things; attr_accessor adds functions for interacting with a variable.

module ToMix
    @module_var = "module_var"
    attr_accessor :mixed_var
    def initialize
      @mixed_var = "mixed_var"
    end

    def mix_function
        puts "mix_function: #{@mixed_var}"
    end
    def self.module_function
        @module_var
    end
end

class Mixed
  include ToMix
end

Mixed.new.mixed_var

值得注意的是,

"".extend(ToMix).mixed_var == nil # no error, but no value, interesting!

但是

(a = "".extend(ToMix)).mixed_var = "interesting"
a.mixed_var == "interesting"

ToMix.module_function == "module_var"

https://stackoverflow.com/a/151774/171916 http://www.natontesting .com/2009/09/28/access-instance-variables-declared-in-ruby-modules/ 如何在Ruby中动态更改继承

如果我错了,那比我应该纠正的要聪明的多,但是模块和类定义本身就是对象.因此,在模块定义中定义@var会将var添加到模块对象本身

Those wiser than I should correct me if I'm wrong, but module and class definitions are themselves objects. Defining a @var in a module definition thus adds the var to the module object itself

比我更正的建议还更明智:类和模块定义的行为类似于单例,但它们本身并不是对象.您可以将方法外部的def self.bacon@var视为c ++静态方法和变量,但是即使您在实例中,它们也可以像静态一样被访问.

Those wiser than I have corrected me: While class and module definitions sort of behave like a singleton, they are not themselves objects. You can think of def self.bacon and @var outside of methods as c++ static methods and variables, but they can /only/ be access like a static, even if you're in an instance.

这篇关于Ruby,mixin实例变量和方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆