Class variables and deleting objects

Being only a few hours into learning Ruby I’ve read very little about
class variables yet but decided to experiment with them anyway as an
alternative to using a global variable. I typed in the code below and
having created a few ‘Cheese’ objects was (un)surprised to find that it
just worked. Each cheese is assigned it’s own idnumber.

I’d just like to know if using class variables in this way is likely to
cause any problems?

Secondly, from the little I’ve discovered so far, is it correct that
there is no way to delete an object when it is no longer required? How
would I handle millions of transient objects, for example particles that
live and die. Over the life of the program millions of such objects
might be created but only thousands may be ‘alive’ at any one time.

class Cheese
@@idcounter=0
attr_accessor :name, :flavour
@idnumber
def initialize
@idnumber = @@idcounter
@@idcounter += 1
end
end

TIA

Paul

On Fri, Feb 21, 2014 at 1:02 PM, Paul R. [email protected]
wrote:

I’d just like to know if using class variables in this way is likely to
cause any problems?

Most people coming from other languages with class-vars are caught
off-guard by a big gotcha. In Ruby, the parent classes share with
their subclasses not only the fact that the class-var exists, but
it’s the same var.

You seem to be actually taking advantage of that, so that if for
instance I subclass Cheese into Stilton and Wensleydale and
instantiate a few of each, each individual object will have its own
unique @idnumber. So, I’d say that this particular usage of it is
unlikely to cause problems. But watch out for it in other contexts
where you might be used to “normal” class-var behavior from other
languages.

This is one of the things covered in the slides from my “Ruby Gotchas”
presentation, at:

https://docs.google.com/presentation/d/1cqdp89_kolr4q1YAQaB-6i5GXip8MHyve8MvQ_1r6_s

Secondly, from the little I’ve discovered so far, is it correct that
there is no way to delete an object when it is no longer required?

Generally speaking, that is correct, at least without hacking the
interpreter. Trust the garbage collector, or tweak its parameters if
need be.

-Dave

Thanks Dave, that’s very helpful.

Just to return to my last point, I don’t see how the garbage collector
would help. How would it know which objects were ‘dead’ and could be
removed?

Cheers

Paul

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs