Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Programming Techniques: simple yet not so simple object manipulation

Tags:

math

ruby

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!

like image 319
Shyam Avatar asked Apr 12 '10 20:04

Shyam


1 Answers

Could you create a PieSlice object, and each Pie would have an array of PieSlices?

like image 143
JRL Avatar answered Oct 05 '22 06:10

JRL