Bala
Bala

Reputation: 11274

Ruby super value when argument is missing in subclass

 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

Is it possible to create a AnotherBike instance 'AnotherBike.new' that will take default value for 'gears' from super when argument is not given?

so for 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

I am using Ruby 1.9.3.

Upvotes: 1

Views: 262

Answers (4)

fl00r
fl00r

Reputation: 83680

You can change an order of args to make it little more elegant

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)

to support your examples @Matzi answer will be ok

Upvotes: 1

Matzi
Matzi

Reputation: 13925

Class:

class AnotherBike < Bike
  attr_reader :seats

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

Usage:

AnotherBike.new(nil, 13)

It should work, but this can be a bit redundant.

Upvotes: 1

Hugo Wood
Hugo Wood

Reputation: 2270

I might be drifting a little too far from the actual question, but it looks like you might gain from using composition instead of inheritance. I don't know what the context is though.

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

Upvotes: 0

Gaurav Agarwal
Gaurav Agarwal

Reputation: 14853

Why not send a hash instead?

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

you have to call it as: AnotherBike.new({:g => 3, :s => 4})

Upvotes: 0

Related Questions