Setting Class Variables with Class Method

T

Thijs De vries

Hey guys,
I was wondering how to set class variables using a class method, for
example:

class Foo
@@this_works = 'hello'
@@this_does_not = self.goodbye

def self.goodbye
return 'goodbye'
end
end

Is there an equivalent to initialize but for loading class variables? I
was able to get something above to work by adding a method:

def self.this_does_not=()
@@this_does_not = var
end

and than calling:

Foo.this_does_not = Foo.goodbye

but this would force me to use public methods and in terms of
organization, I like to define class methods at the top.
 
J

Jesús Gabriel y Galán

Hey guys,
I was wondering how to set class variables using a class method, for
example:

=A0class Foo
=A0 @@this_works =3D 'hello'
=A0 @@this_does_not =3D self.goodbye

=A0 def self.goodbye
=A0 =A0 return 'goodbye'
=A0 end
=A0end

You can't call a method before defining it. The call to self.goodbye
is executed at that point, but the method goodbye doesn't exist yet.
Try this:

irb(main):001:0> class Foo
irb(main):002:1> def self.goodbye
irb(main):003:2> "goodbye"
irb(main):004:2> end
irb(main):005:1> @@this_works =3D 'hello'
irb(main):006:1> @@this_does_not =3D self.goodbye
irb(main):007:1> end
=3D> "goodbye"
irb(main):011:0> Foo.send:)class_variable_get, "@@this_does_not")
=3D> "goodbye"

With all the caveats around being sure that you really need class
variables and not class instance variables, and so on...

Hope this helps,

Jesus.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,979
Messages
2,570,185
Members
46,727
Latest member
FelicaTole

Latest Threads

Top