2013-02-19 35 views
1
class Bike 
    attr_reader :gears 

    def initialize(g = 5) 
    @gears = g 
    end 
end 

class AnotherBike < Bike 
    attr_reader :seats 

    def initialize(g, s = 2) 
    super(g) 
    @seats = s 
    end 
end 

是否有可能創建一個AnotherBike實例「AnotherBike.new」 時沒有給出參數,將採取從超級「齒輪」默認值?紅寶石超值參數時在子類中缺少

所以e.g

my_bike = AnotherBike.new 
... 
my_bike.gears #=> 5 
my_bike.seats #=> 2 

my_bike = AnotherBike.new(10) 
... 
my_bike.gears #=> 10 
my_bike.seats #=> 2 

my_bike = AnotherBike.new(1,1) 
... 
my_bike.gears #=> 1 
my_bike.seats #=> 1 

我使用Ruby 1.9.3。

回答

1

你可以改變形式參數的順序,使其多一點優雅

class AnotherBike < Bike 
    attr_reader :seats 

    def initialize(s = 2, g = nil) 
    g ? super(g) : super() 
    @seats = s 
    end 
end 

AnotherBike.new() 
AnotherBike.new(4) 
AnotherBike.new(4, 6) 

來支持你的例子@Matzi答案將確定

1

類:

class AnotherBike < Bike 
    attr_reader :seats 

    def initialize(g = nil, s = 2) 
    g ? super() : super(g) 
    @seats = s 
    end 
end 

用法:

AnotherBike.new(nil, 13) 

它應該工作,但是這可能是有點多餘。

+1

我想'super'會把所有ARGS,如果你不把它傳遞明確的,所以你應該叫'超()'這樣 – fl00r 2013-02-19 12:58:32

0

爲什麼不發送散列?

class Bike 
    attr_reader :gears 

    def initialize(attributes) 
    @gears = attributes.delete(:g) || 5 
    end 
end 

class AnotherBike < Bike 
    attr_reader :seats 

    def initialize(attributes) 
    @seats = attributes.delete(:s) || 2 
    super(attributes) 
    end 
end 

你要稱呼其爲:AnotherBike.new({:g => 3, :s => 4})

+2

或'AnotherBike.new(G:3,S:4) '在Ruby ** 1.9 **中。 – 2013-02-19 12:57:33

+0

不確定OP是在哪個版本上! – 2013-02-19 12:58:12

0

我可能會偏離實際問題太遠,但看起來您可能會從使用組合而不是繼承獲得收益。我不知道上下文是什麼。

class Gears 
    def initialize(count = 5) 
    @count = count 
    end 
end 

class Seats 
    def initialize(count = 2) 
    @count = count 
    end 
end 

class Bike 
    def initialize(gears, seats) 
    @gears = gears 
    @seats = seats 
    end 
end