0
class Card

  attr_accessor :number, :suit

  def initialize(number, suit)
    @number = number
    @suit = suit
  end

  def to_s
    "#{@number} of #{@suit}"
  end
end

I'm assuming this creates a new array correct? But why the use of the AT symbol? When should I use it and not use it?

@stack_of_cards = []

@stack << Card.new("A", "Spades")

puts @stack

# => BlackjackGame.rb:17: undefined method `<<' for nil:NilClass (NoMethodError)

Any ideas why this error is firing?

edgerunner
  • 14,873
  • 2
  • 57
  • 69

2 Answers2

2

Exactly as it says in error: variable @stack is not defined (or nil).
Did you mean @stack_of_cards << .. instead?

Nikita Rybak
  • 67,365
  • 22
  • 157
  • 181
  • Yeah, that was the error. On a related note, when do I need to use the AT symbol? Because I remove the AT symbol and the script still runs well. Thank you. –  Feb 20 '11 at 22:38
  • @Sergio It's used to declare global variables (especially often in Rails). In a simple script, there's little reason to use it. – Nikita Rybak Feb 20 '11 at 22:39
  • 3
    The @ symbol does NOT declare a global variable. It references an instance variable. – Chuck Feb 20 '11 at 22:59
  • @Sergio Sorry, I'm stupid, with `@` you denote instance variables of object :) And with `@@` - instance variables of class (much like `static` in java) – Nikita Rybak Feb 20 '11 at 23:00
2

If you had warnings on (ruby -W2 script_name.rb), you would have got a warning that @stack is not merely nil, but undefined. See How do I debug Ruby scripts? for more hints on how to debug.

Community
  • 1
  • 1
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338