Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static variables in ruby

Tags:

ruby

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 student object we create, its id number should get incremented automatically.

I thought creating class variable as a static will do.

like image 776
levirg Avatar asked Mar 10 '10 11:03

levirg


People also ask

What is a static variable in Ruby?

In Ruby, there are two implementations for the static keyword: Static Variable: A Class can have variables that are common to all instances of the class. Such variables are called static variables. A static variable is implemented in ruby using a class variable.

What are Ruby class variables?

Used declare variables within a class. There are two main types: class variables, which have the same value across all class instances (i.e. static variables), and instance variables, which have different values for each object instance.

How do you set a static variable?

If a variable is static , the variable is assigned memory once and all objects of the class access the same variable. A static variable can be created by adding the static keyword before the variable during declaration.

Do Ruby variables have types?

There are different types of variables in Ruby: Local variables. Instance variables. Class variables.


1 Answers

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 
like image 93
sepp2k Avatar answered Sep 28 '22 05:09

sepp2k