static variables in ruby

前端 未结 2 627
我在风中等你
我在风中等你 2020-12-24 10:17

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

For example, if we want to create a Student class and for each

相关标签:
2条回答
  • 2020-12-24 10:46

    Using the accepted answer as the definition of static variable can be dangerous, and it is a common error that I have seen in a lot of Ruby code.

    Something like @@foos is shared among ALL subclasses. However, most programmers expect static variables to have scope only within the class where they are defined.

    If you are looking for static variables in the sense of most languages, where their scope is only their own class, look at this SO answer

    Also this blog post has a nice example of the surprise most programmers will get:

    http://www.railstips.org/blog/archives/2006/11/18/class-and-instance-variables-in-ruby/

    0 讨论(0)
  • 2020-12-24 10:51

    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
    
    0 讨论(0)
提交回复
热议问题