views:

85

answers:

3

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
+6  A: 

You can define one by appending the equals sign to the end of the method name:

def self.total_people=(v)
  @@total_people = v
end

You're putting all instances in @@current_people you could define total_people more accurately:

def self.total_people
  @@current_people.length
end

And get rid of all the @@total_people related code.

jdeseno
A: 

One approach that didn't work was the following:

module PersonClassAttributes
  attr_writer :nationalities
end

class Person
  extend PersonClassAttributes
end

I suspect it's because attr_writer doesn't work with modules for some reason.

I'd like to know if there's some metaprogramming way to approach this. However, have you considered creating an object that contains a list of people?

Andrew Grimm
+3  A: 

I think this solves your problem:

class Person
  class << self
    attr_accessor :foobar
  end

  self.foobar = 'hello'
end

p Person.foobar # hello

Person.foobar = 1

p Person.foobar # 1

Be aware of the gotchas with Ruby's class variables with inheritance - Child classes cannot override the parent's value of the class var. A class instance variable may really be what you want here, and this solution goes in that direction.

x1a4