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?

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

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.
@Sergio It's used to declare global variables (especially often in Rails). In a simple script, there's little reason to use it.
The @ symbol does NOT declare a global variable. It references an instance variable.
@Sergio Sorry, I'm stupid, with @ you denote instance variables of object :) And with @@ - instance variables of class (much like static in java)
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.

Comments

Your Answer

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