9.3 Data and Methods
Objects are made up of two important concepts: the data the object holds (the instance variables) and the actions the object can perform (the methods).
9.3.1 Grouping Data and Methods
The previous section detailed how to create and instantiate an
object of an Account
class, and while
reading it you might have been thinking to yourself, “How was I supposed
to know that an Account
class needs a
balance
variable?” The answer is that
no class requires any particular piece of data, but classes are used to
group related pieces of data together, and it only makes sense that an
account has a balance. Likewise, there are other things that would come
as a part of a bank account. Depending on the nature of the bank
account, the type of data included would change. For example, a savings
account wouldn’t necessarily include the same data as a checking
account. Regardless, we are talking about a generic bank account, and
additional data possibly included are name, phone number, Social
Security number, minimum balance, and maximum balance. We now introduce
two additional instance variables to our Account
class, as shown in Example 9-3.
1
class
Account
2
def
initialize
(
balance
,
name
,
phone_number
)
3
@balance
=
balance
4
@name
=
name
5
@phone_number
=
phone_number
6
end
7
end
Gem of Wisdom
Note that the instance variables balance
, name
, and phone_number
are assigned in the order the
parameters were passed to the initialize
method; however, ...
Get Computer Science Programming Basics in Ruby now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.