SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Dec 2006
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    initializing Ruby class state

    Newbie question: I have a little class in which I want to initialize some state without asking the class's clients to pass in that state through the constructor. Here's what I mean:

    class Game


    def initialization
    @currentPlayer = 'X'
    end

    attr_reader :currentPlayer

    end

    game = Game.new
    puts game.currentPlayer


    I want to set the @currentPlayer instance variable to a literal value on initialization. But doing it as above, the code below the class always returns nil from game.currentPlayer.

    What Ruby idiom am I not following here? Why shouldn't I get the expected 'X' back?

    thanks,

    Chuck

  2. #2
    SitePoint Guru
    Join Date
    Aug 2005
    Posts
    986
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The method is called `initialize`.

  3. #3
    SitePoint Member
    Join Date
    Dec 2006
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    thanks - duh, that was it


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •