[英]How to access variables from an extended class in ruby
In most languages you can do something like the following: 在大多数语言中,您可以执行以下操作:
class a {
this.property = 'prop'
}
class b extends a {
puts this.property //prints 'prop'
}
How does this work in ruby? 红宝石如何工作? My initial thought was something like
我最初的想法是
class A
@property = 'prop'
end
class B < A
puts @property
end
But this doesn't work. 但这是行不通的。 Ruby has the
self
keyword but that seems from what I can tell to be reserved for methods. Ruby有
self
关键字,但是从我的判断看来,它似乎是为方法保留的。 Can classes inherit variables in ruby? 类可以在ruby中继承变量吗?
Yes they can, and here's a snippet that shows how. 是的,他们可以,并且下面的代码片段演示了如何操作。
class A2
def initialize
@foo = 42
end
end
class B2 < A2
def print_foo
puts @foo
end
end
# Prints 42
B2.new.print_foo
The above code defines a class A2
, with a constructor that defines and sets an instance variable @foo
. 上面的代码定义了一个类
A2
,并带有一个定义并设置实例变量@foo
。 Class B2
extends A2
, and defines a method that uses @foo
. B2
类扩展了A2
,并定义了一个使用@foo
的方法。
I think the issue with your code is that @property
is not assigned a value, as the assignment isn't in a method that gets called at any point. 我认为您的代码存在的问题是
@property
没有分配值,因为分配没有在任何时候被调用的方法中。
Yes. 是。 You need to init instance variables in the
initialize
method. 您需要在
initialize
方法中初始化实例变量。
See an example: 看一个例子:
class A
attr_accessor :property
def initialize
self.property = 'prop'
end
end
class B < A
end
puts B.new.property # prints "prop"
Variables starting with an @
sigil are instance variables . 开头的变量
@
印记是实例变量 。 They belong to a particular instance (ie "object"). 它们属于特定实例(即“对象”)。
You have two objects in your code, one object is the class A
, the second object is the class B
. 您的代码中有两个对象,一个对象是
A
类,第二个对象是B
类。 Each of those two objects has its own instance variables. 这两个对象中的每一个都有其自己的实例变量。
A
has an instance variable called @property
with the value 'prop'
. A
有一个名为@property
的实例变量,其值是'prop'
。 B
has no instance variables, however, uninitialized instance variables evaluate to nil
instead of raising an exception, so, you don't get an error, but it evaluates to nil
. B
没有实例变量,但是,未初始化的实例变量的值为nil
而不是引发异常,因此,您不会收到错误,但其值为nil
。
You cant' inherit variables. 你不能继承变量。 The only thing you can inherit in Ruby, are methods:
在Ruby中唯一可以继承的是方法:
class A
def self.property
'prop'
end
end
class B < A
puts property
end
# prop
Ruby also has class variables that start with an @@
sigil. Ruby还具有以
@@
sigil开头的类变量。 These are shared across the entire class hierarchy: 这些在整个类层次结构中共享:
class A
@@property= 'prop'
end
class B < A
puts @@property
end
# prop
However, class variables are almost never used in Ruby, because of the wide scope they have, almost like globals. 但是,类变量几乎从未在Ruby中使用,因为它们的作用域很广,就像全局变量一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.