ruby 中的静态变量 [英] static variables in ruby

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

问题描述

我刚刚了解了 php 中的静态变量.ruby 中有类似的东西吗?

I just learned about static variables in php. Is there anything like that in ruby?

例如,如果我们想创建一个 Student 类,并且对于我们创建的每个 student 对象,它的 id 号应该自动递增.

For example, if we want to create a Student class and for each student object we create, its id number should get incremented automatically.

我认为将类变量创建为静态就可以了.

I thought creating class variable as a static will do.

推荐答案

类变量在所有实例之间共享(这就是它们被称为类变量的原因),因此它们将执行您想要的操作.它们也是继承的,有时会导致相当混乱的行为,但我认为这不会成为问题.下面是一个使用类变量来计算创建了多少个实例的类的示例:

Class variables are shared between all instances (which is why they're called class variables), so they will do what you want. They're also inherited which sometimes leads to rather confusing behavior, but I don't think that will be a problem here. Here's an example of a class that uses a class variable to count how many instances of it have been created:

class Foo
  @@foos = 0

  def initialize
    @@foos += 1
  end

  def self.number_of_foos
    @@foos
  end
end

Foo.new
Foo.new
Foo.number_of_foos #=> 2

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

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