Normally when we want to talk about a string, we will just call it a string. However, we could also call it a string object. Sometimes programmers might call it an instance of the class String, but it’s just another way of saying string. An instance of a class is just an object of that class.
So, instance variables are just an object’s variables. A method’s local variables last until the method is finished. An object’s instance variables, on the other hand, will last as long as the object does. To tell instance variables from local variables, they have @ in front of their names:
class Die |
|
def roll |
@number_showing = 1 + rand(6) |
end |
|
def showing |
@number_showing |
end |
|
end |
|
die = Die.new |
die.roll |
puts die.showing |
puts die.showing |
die.roll |
puts die.showing |
puts die.showing |
1 |
1 |
2 |
2 |
Very nice! roll rolls the die, and showing tells us which number is showing. However, what if we try to look at what’s showing before we’ve rolled the die (before we’ve set @number_showing)?
class Die |
|
def roll |
@number_showing = 1 + rand(6) |
end |
|
def showing |
@number_showing |
end |
end |
# Since I'm not going to use this die again, |
# I don't need to save it in a variable. |
puts Die.new.showing |
|
Hmmm…well, at least it didn’t give us an error. Still, it doesn’t really make sense for a die to be “unrolled,” or whatever nil is supposed to mean here. It would be nice if we could set up our new Die object right when it’s created. That’s what initialize is for; as soon as an object is created, initialize is automatically called on it:
class Die |
|
def initialize |
# I'll just roll the die, though we could do something else |
# if we wanted to, such as setting the die to have 6 showing. |
roll |
end |
|
def roll |
@number_showing = 1 + rand(6) |
end |
|
def showing |
@number_showing |
end |
|
end |
|
puts Die.new.showing |
6 |
(One thing to note here: in the previous code, we are first just defining what the Die class is by defining the methods initialize, roll, and showing. However, none of these is actually called until the very last line.)
Very nice. Our dice are just about perfect. The only feature that might be missing is a way to set which side of a die is showing…why don’t you write a cheat method that does just that? Come back when you’re done (and when you tested that it worked, of course). Make sure that someone can’t set the die to have a 7 showing; you’re cheating, not bending the laws of logic.
3.133.124.145