1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Ruby Quiz #164 - Price Ranges

# The PriceRange class represents both the desired price range of the
# shopper and the price ranges of the companies.
# 
#   company_a = PriceRange.new(:low => 1_000, :high => 3_000)
#   company_b = PriceRange.new(:low => 6_000, :high => 10_000)
#   company_c = PriceRange.new(:low => 500,   :high => 2_500)
# 
#   customer  = PriceRange.new(:low => 2_500, :high => 5_000)
# 
# The low and high points are both optional and default to zero and
# infinity respectively.
# 
# Once you have the price ranges set up, it's as easy as using the
# select method to determine which company the shopper should examine.
# 
#   customer.select(company_a, company_b, company_c)
#     # => [company_a, company_c]
# 
# I decided against using Ruby's Range class for unremembered reasons.
# 
# I didn't leave anything out did I?
class PriceRange
  attr_reader :low, :high
  
  def initialize(opts={})
    @low  = opts[:low] || 0
    @high = opts[:high] || 1.0 / 0.0
  end
  
  def includes_price?(price)
    price >= @low and price <= @high
  end
  
  def includes_edge_of?(other)
    includes_price?(other.low) or includes_price?(other.high)
  end
  
  def select(*ranges)
    ranges.select {|range| self.includes_edge_of?(range) or range.includes_edge_of?(self)}
  end
end