Ruby Programming Techniques: Simple But Not Simple Object Handling

I want to create an object, say, a pie.

class Pie 
  def initialize(name, flavor) 
    @name = name 
    @flavor = flavor 
  end 
end

But the pie can be divided into 8 parts, half or just a whole pie. For argumentation, I would like to know how I can give each Pie object a price for 1/8, 1/4 or the 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 created fifteen Pie objects, and I accidentally pulled out some fragments using a method such as

getPieceOfPie(pie_name)

How can I get the value of all available pies, which are whole and leftover parts? In the end, using a method like:

   myCurrentInventoryHas(pie_name)
   # output: 2 whole strawberry pies and 7 pieces.

I know I'm new to Ruby. Thanks for your answers, comments and help!

+5
source share
4 answers

Pie PiePiece

class Pie
  attr_accessor :pieces
  def initialize
    self.pieces = []
  end

  def add_piece(flavor)
    raise "Pie cannot have more than 8 pieces!" if pieces.count == 8
    self.pieces << PiePiece.new(flavor)
  end

  # a ruby genius could probably write this better... chime in if you can help
  def inventory
    Hash[pieces.group_by(&:flavor).map{|f,p| [f, p.size]}]
  end

end

class PiePiece
  attr_accessor :flavor
  def initialize(flavor)
    self.flavor = flavor
  end
end

p = Pie.new
p.add_piece(:strawberry)
p.add_piece(:strawberry)
p.add_piece(:apple)
p.add_piece(:cherry)
p.add_piece(:cherry)
p.add_piece(:cherry)

p.inventory.each_pair do |flavor, count|
  puts "Pieces of #{flavor}: #{count}"
end

# output
# Pieces of strawberry: 2
# Pieces of apple: 1
# Pieces of cherry: 3
+2

PieSlice, Pie PieSlices?

+3

The Pie class may have a counter to indicate how much of it remains. The method getPieceOfPiewill change this counter. The method myCurrentInventoryHascould then look at each pie and see how many of the pie the counter is studying.

+1
source

A piece of cake is not a cake.

(speaking in terms of oo, the object must have a clear responsibility, making the object a pie, and a slice cannot be an explicit assignment of responsibility).

0
source

All Articles