从外部访问Class的实例变量

时间:2010-11-17 09:01:33

标签: ruby variables instance-variables class-variables

我理解(我认为)Ruby中类的类变量和实例变量之间的区别。

我想知道如何从OUTSIDE那个类访问类的实例变量。

从内部(也就是在类方法而不是实例方法中),可以直接访问它,但是从外部可以进行MyClass.class.[@$#]variablename吗?

我没有任何具体的理由这样做,只是学习Ruby并想知道是否可能。

3 个答案:

答案 0 :(得分:6)

class MyClass

    @my_class_instance_var = "foo"

    class << self
        attr_accessor :my_class_instance_var
    end

end

puts MyClass::my_class_instance_var

上述产量:

>> foo

我相信Arkku演示了如何从类外部访问类变量(@@),而不是类实例变量(@)。

我从这篇文章中提到了上述内容:Seeing Metaclasses Clearly

答案 1 :(得分:2)

Ruby有Class,Class Object和Instance。

  

Class变量属于Class。
Class实例变量   属于类对象

类变量:

  

在班级及其实例中可访问   attr_accessor不适用于类变量。

类实例变量:

  

只能通过班级访问。
  如果你在类中定义它而不是在类对象中定义它,则attr_accessor可以工作。

class A
    @b = 1
    class << self
        attr_accessor :b
    end
end

在类实例变量b的实例中定义getter和setter:

class A
    @b = 1
    class << self
        attr_accessor :b
    end
    def b
        A.b
    end
    def b=(value)
        A.b=value
    end
end

现在可以通过所有者Class及其实例访问类实例变量b 作为一个几天的红宝石学习者,这是我能做的最多。

`irb(main):021:0* class A
irb(main):022:1> @b = 1
irb(main):023:1> class << self
irb(main):024:2> attr_accessor :b
irb(main):025:2> end
irb(main):026:1> def b
irb(main):027:2> A.b
irb(main):028:2> end
irb(main):029:1> def b=(v)
irb(main):030:2> A.b=v
irb(main):031:2> end
irb(main):032:1> end
=> :b=
irb(main):033:0> A.b
=> 1
irb(main):034:0> c = A.new
=> #<A:0x00000003054440>
irb(main):035:0> c.b
=> 1
irb(main):036:0> c.b= 50
=> 50
irb(main):037:0> A.b
=> 50
irb(main):038:0>`

是的,我开始不喜欢红宝石......等一个更好的解决方案。

答案 2 :(得分:1)

在红宝石中,你可以通过两种方式实现这一目标

  1. 手动定义getter和setter
  2. 使用attr_ * methods
  3. 让我为您详细说明上述方法,

    手动定义getter和setter

    class Human
      def sex=(gender)
        @sex = gender
      end
    
      def sex
        @sex
      end
    end
    
    //from outside  class 
    human = Human.new
    // getter method call 
    puts human.sex
    // setter method call to explicitly set the instance variable 
    human.sex = 'female'
    
    puts human.sex 
    // now this prints female which is set
    

    使用attr_ *方法

    class Human
      attr_accessor :sex
    end
    
    //from outside 
    
    human = Human.new
    // getter method call 
    puts human.sex
    // setter method call to explicitly set the instance variable 
    human.sex = 'female'
    
    puts human.sex 
    // now this prints female which is set 
    

    attr_accessor会在内部为您创建setter和getter方法,如果您只想使用setter,则可以使用attr_writer,如果只需要getter,则可以使用attr_reader。

    我希望,我回答了你的问题