Ruby Programming Techniques: simple yet not so simple object manipulation
Posted
by Shyam
on Stack Overflow
See other posts from Stack Overflow
or by Shyam
Published on 2010-04-12T20:35:33Z
Indexed on
2010/04/12
20:42 UTC
Read the original article
Hit count: 504
Hi,
I want to create an object, let's say a Pie.
class Pie
def initialize(name, flavor)
@name = name
@flavor = flavor
end
end
But a Pie can be divided in 8 pieces, a half or just a whole Pie. For the sake of argument, I would like to know how I could give each Pie object a price per 1/8, 1/4 or per whole. I could do this by doing:
class Pie
def initialize(name, flavor, price_all, price_half, price_piece)
@name = name
@flavor = flavor
@price_all = price_all
@price_half = price_half
@price_piece = price_piece
end
end
But now, if I would create fifteen Pie objects, and I would take out randomly some pieces somewhere by using a method such as
getPieceOfPie(pie_name)
How would I be able to generate the value of all the available pies that are whole and the remaining pieces? Eventually using a method such as:
myCurrentInventoryHas(pie_name)
# output: 2 whole strawberry pies and 7 pieces.
I know, I am a Ruby nuby. Thank you for your answers, comments and help!
© Stack Overflow or respective owner