Pardon the total newbiew question but why is @game_score always nil?
#bowling.rb
class Bowling
@game_score = 0
def hit(pins)
@game_score = @game_score + pins
end
def score
@game_score
end
end
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Let’s walk through the code, shall we?
At this point (1), we are still inside the class
Bowling. Remember: classes are just objects like any other. So, at this point you are assigning0to the instance variable@game_scoreof the class objectBowling.Now (2), we are inside an instance method of the
Bowlingclass. I.e.: this is a method that is going to belong to an instance ofBowling. So, now the instance variable@game_scorebelongs to an instance of theBowlingclass, and not to the class itself.Since this instance variable is never initialized to anything, it will evaluate to
nil(in Ruby, uninitialized variables always evaluate tonil), so this evaluates to@game_score = nil + pinsand sincenildoesn’t have a#+method, this will result in aNoMethodErrorexception being raised.And here (3), we are again inside an instance method of the
Bowlingclass. This will always evaluate tonil, for the reason I outlined above:@game_scoreis never initialized, therefore it evaluates tonil.We can use Ruby’s reflection capabilities to take a look at what’s going on:
Now let’s inject a value into the instance variable:
So, we see that everything works as it should, we only need to figure out how to make sure the instance variable gets initialized.
To do that, we need to write an initializer method. Strangely, the initializer method is actually a private instance method called
initialize. (The reason whyinitializeis an instance method and not a class method, is actually quite simple. Ruby splits object creation in two phases: memory allocation and object initialization. Memory allocation is done by a class method calledallocand object initialization is done by an instance method calledinitialize. (Objective-C programmers will recognize this.) The reason whyallocis a class method is simply that at this point in the execution there is no instance yet. And the reason thatinitializeis an instance method is that object initialization is obviously per-object. As a convenience, there is a standard factory class method callednewthat calls bothallocandinitializefor you.)Let’s test this:
BTW: just some minor Ruby style tips: indentation is 2 spaces, not 1 tab. And your
hitmethod would more idiomatically be@game_score += pins.