Static variables in ruby

I just found out about static variables in php. Is there anything like this in a ruby?

For example, if we want to create a Student class and for each Student object we create, its identifier number should automatically increase.

I thought creating a class variable would be static.

+60
ruby
Mar 10 '10 at 11:18
source share
2 answers

Class variables are shared between all instances (therefore they are called class variables), so they will do what you want. They are also inherited, which sometimes leads to rather confusing behavior, but I don't think this will be a problem here. Here is an example of a class that uses a class variable to calculate 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 
+95
Mar 10 '10 at 11:24
source share

Using the accepted answer, as defining a static variable can be dangerous, and this is a common mistake that I saw in a lot of Ruby code.

Something like @@foos is split between ALL subclasses. However, most programmers expect static variables to have a scope only inside 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, check out 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/

+13
Dec 30 '14 at 19:35
source share



All Articles