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.
On Wed, Oct 20, 2010 at 6:04 PM, Thijs De vries [email protected]
wrote:
end
end
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 = ‘hello’
irb(main):006:1> @@this_does_not = self.goodbye
irb(main):007:1> end
=> “goodbye”
irb(main):011:0> Foo.send(:class_variable_get, “@@this_does_not”)
=> “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.