我理解(我认为)Ruby类中类变量和实例变量的区别。
我想知道如何从类的外部访问其实例变量。
在类方法中可以直接访问,但是从外部是否有一种方式可以使用MyClass.class.[@$#]variablename
?
我没有任何具体原因去这样做,只是学习Ruby并且想知道是否有可能。
我理解(我认为)Ruby类中类变量和实例变量的区别。
我想知道如何从类的外部访问其实例变量。
在类方法中可以直接访问,但是从外部是否有一种方式可以使用MyClass.class.[@$#]variablename
?
我没有任何具体原因去这样做,只是学习Ruby并且想知道是否有可能。
class MyClass
@my_class_instance_var = "foo"
class << self
attr_accessor :my_class_instance_var
end
end
puts MyClass::my_class_instance_var
>> foo
class A
@b = 1
class << self
attr_accessor :b
end
end
class A
@b = 1
class << self
attr_accessor :b
end
def b
A.b
end
def b=(value)
A.b=value
end
end
现在可以通过owner类及其实例访问类实例变量b。
作为一个几天前开始学习 Ruby 的学习者,这是我所能做的最多的。
`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>`
是的,我开始不喜欢 Ruby...有更好的解决方案。
在 Ruby 中,你可以通过两种方式实现这个目标
让我为您详细解释上述方法,
手动定义 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。
希望我回答了您的问题。