子类中缺少参数时的Ruby超值

时间:2013-02-19 12:47:15

标签: ruby arguments super

 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 个答案:

答案 0 :(得分: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 :(得分: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答案会没问题

答案 2 :(得分: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})

答案 3 :(得分: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