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”,当未给出参数时,该实例将从 super 获取“gears”的默认值?

所以例如

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。

4

4 回答 4

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)

它应该可以工作,但这可能有点多余。

于 2013-02-19T12:53:35.093 回答
1

您可以更改 args 的顺序以使其更优雅

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 答案就可以了

于 2013-02-19T13:00:45.547 回答
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})

于 2013-02-19T12:54:15.360 回答
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
于 2013-02-19T13:07:26.567 回答