2

I have this class:

class Game
  attr_accessor :player_fleet, :opponent_fleet
  @player_fleet = []
  @opponent_fleet = []
  ...
end

and create an instance like this:

my_game = Game.new

then use it like this:

my_game.opponent_fleet << opponent

which gives me this error:

undefined method `<<' for nil:NilClass (NoMethodError)

Why can't I treat an array like this? Do I have to create a method to push objects into the array?

1
  • in effect, you have to harness the initialize method to treat an array like this Commented Mar 7, 2014 at 1:07

1 Answer 1

4

You initialize @opponent_fleet at class level, so it's an instance variable of the class, not of the generated objects. Remember that in Ruby, even classes are objects :)

irb(main):001:0> class Game
irb(main):002:1>   @foo = 3
irb(main):003:1> end
irb(main):004:0> Game.instance_eval { @foo }
=> 3
irb(main):005:0> Game.new.instance_eval { @foo }
=> nil

You want to initialize it in a constructor instead:

class Game
  attr_accessor :player_fleet, :opponent_fleet

  def initialize
    @player_fleet = []
    @opponent_fleet = []
  end
end
Sign up to request clarification or add additional context in comments.

4 Comments

@theTinMan As much as I appreciate your edit, I want the smiley back!
Remember, Stack Overflow is supposed to be the Wikipedia of programming. When do you see smileys in formal documents and encyclopedias? Don't be surprised if someone else comes along and removes it.
OK this is a subtle difference I haven't dealt with before. Thanks!
@theTinMan: I'm not surprised at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.