Ruby类变量 [英] Ruby class variables

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

问题描述

ruby​​类实例的东西让我头痛。我明白这个...

  class Foo 
@var ='bar'
end

... @var 是一个变量



这里是创建类的实例。



我将在Python中做的一个例子:

  class Fish:
var ='fish'
def v(self):
return self.var

class Trout(Fish):
var ='trout'

class Salmon :
var ='salmon'

print Trout()。v()
print Salmon().v()
/ pre>

哪些输出:

  trout 
salmon

如何在ruby中做同样的事?

解决方案

检查这篇文章,它真的解释了它的深入。



基本上,如果你想继承,那么使用一个实例变量。


The ruby class-instance stuff is giving me a headache. I understand given this...

class Foo
  @var = 'bar'
end

...that @var is a variable on the created class's instance.

But how do I create a sub-class overridable class variable?

Here is an example of what I would do in Python:

class Fish:
var = 'fish'
def v(self):
    return self.var

class Trout(Fish):
    var = 'trout'

class Salmon(Fish):
    var = 'salmon'

print Trout().v()
print Salmon().v()

Which outputs:

trout
salmon

How do I do the same thing in ruby?

解决方案

Check this article out, it really explains it in-depth.

Basically, if you want inheritance then use an instance variable.

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

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