2016-12-01 79 views
2

我正在編寫POODR的第8章,將組合對象與組合。不過,我似乎無法讓這個例子的工作:Ruby中的布爾型參數錯誤

class Bicycle 
    attr_reader :size, :parts 

    def initialize(args = {}) 
    @size = args[:size] 
    @parts = args[:parts] 
    end 

    def spares 
    parts.spares 
    end 
end 

require 'forwardable' 
class Parts 
    extend Forwardable 
    def_delegators :@parts, :size, :each 
    include Enumerable 

    def initialize(parts) 
    @parts = parts 
    end 

    def spares 
    select { |part| part.needs_spare } 
    end 
end 

require 'ostruct' 
module PartsFactory 
    def self.build(config, parts_class = Parts) 
    parts_class.new(
     config.collect do |part_config| 
     create_part(part_config) 
     end 
    ) 
    end 

    def self.create_part(part_config) 
    OpenStruct.new(
     name:  part_config[0], 
     description: part_config[1], 
     needs_spare: part_config.fetch(2, true) 
    ) 
    end 
end 

當我使用road_config

road_config = 
    [['chain',  '10-speed'], 
    ['tire_size', '23'], 
    ['tape_color', 'red']] 

road_bike = 
    Bicycle.new(
    size: 'L', 
    parts: PartsFactory.build(road_config) 
) 

p road_bike.spares.size 

road_bike.spares.size返回3.這是我的預期。然而,當我使用mountain_config

mountain_config = 
    [['chain',  '10-speed'], 
    ['tire_size', '2.1'], 
    ['front_shock', 'Manitou', false], 
    ['rear_shock', 'Fox']] 

mountain_bike = 
    Bicycle.new(
    size: 'L', 
    parts: PartsFactory.build(mountain_config) 
) 

p mountain_bike.spares.size 

我期待看到4,不是如果我從front_shock刪除false它讓默認值(true),mountain_bike.spares.size返回4

爲什麼false使mountain_bike.spares.size返回3?我錯過了什麼?

回答

0

因爲它並不需要一個備用 - 在你的零件類,你選擇需要備用零件:

def spares 
    select { |part| part.needs_spare } 
end 

該代碼將返回所需的備用零件(即needs_spare爲true) 。配置front_shock中的false將此項設置爲false。嘗試將其他部分的needs_spare值設置爲false以查看我的意思。

+0

哇,那真是愚蠢!非常感謝你。 – ogirginc