Setting Class Variables with Class Method

Discussion in 'Ruby' started by Thijs De vries, Oct 20, 2010.

  1. 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.

    --
    Posted via http://www.ruby-forum.com/.
     
    Thijs De vries, Oct 20, 2010
    #1
    1. Advertising

  2. On Wed, Oct 20, 2010 at 6:04 PM, Thijs De vries <> wrot=
    e:
    > 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.
     
    Jesús Gabriel y Galán, Oct 20, 2010
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Pawel_Iks
    Replies:
    3
    Views:
    536
    terminator
    Jul 31, 2007
  2. Joel Gilmore
    Replies:
    5
    Views:
    413
    Joel Gilmore
    Feb 12, 2008
  3. Replies:
    9
    Views:
    961
  4. Phrogz
    Replies:
    1
    Views:
    108
    Phrogz
    Dec 24, 2006
  5. Kyung won Cheon
    Replies:
    0
    Views:
    208
    Kyung won Cheon
    Nov 21, 2008
Loading...

Share This Page