Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Alphonse Cuccurullo
Alphonse Cuccurullo
2,513 Points

Can someone help me with class variables?

class Message 
    @@message_sent = 0
    def initialize(from, to)
        @from = from
        @to = to
        @@message_sent += 1

    end
end

It isnt working.

1 Answer

Clayton Perszyk
MOD
Clayton Perszyk
Treehouse Moderator 48,850 Points

Alphonse,

your code is fine; but you might want to add a class method to access that class variable.

Here's an example:

class Message 
    @@message_sent = 0
    def initialize(from, to)
        @from = from
        @to = to
        @@message_sent += 1
    end

    #class getter method for @@message_sent
    def self.message_sent
        @@message_sent
    end
end

Message.new("here", "eternity")
Message.new("me", "you")
Message.new("you", "me")

puts "#{Message.message_sent} messages sent" # This will print 3, as 3 instances of Message have been created

Best,

Clayton