How do I write a writer method for a class variable in Ruby?

Posted by tepidsam on Stack Overflow See other posts from Stack Overflow or by tepidsam
Published on 2010-05-13T15:11:05Z Indexed on 2010/05/13 15:14 UTC
Read the original article Hit count: 167

Filed under:
|
|

I'm studying Ruby and my brain just froze.

In the following code, how would I write the class writer method for 'self.total_people'? I'm trying to 'count' the number of instances of the class 'Person'.

   class Person

attr_accessor :name, :age

@@nationalities = ['French', 'American', 'Colombian', 'Japanese', 'Russian', 'Peruvian']

@@current_people = []

@@total_people = 0

def self.nationalities #reader @@nationalities end

def self.nationalities=(array=[]) #writer @@nationalities = array end

def self.current_people #reader @@current_people end

def self.total_people #reader @@total_people end

def self.total_people #writer #-----????? end

def self.create_with_attributes(name, age) person = self.new(name) person.age = age person.name = name return person end

def initialize(name="Bob", age=0) @name = name @age = age puts "A new person has been instantiated." @@total_people =+ 1 @@current_people << self end

© Stack Overflow or respective owner

Related posts about ruby

Related posts about classes