0

I am coming from the Java world but I tried to use a base class like this...

class Bicycle
  attr_reader :gears
  def initialize( gears: 1, 
    seats: 2, 
    wheels: 2 )
    @gears = gears
    @seats = seats
    @wheels = wheels
  end  
end  
class CrazyBicycle < Bicycle
  def initialize( seats: 2, 
    wheels: 2 )
    super(101, seats, wheels)
  end  
end  

b = CrazyBicycle.new(3, 4)
puts b.gears

This didn't work and throws Wrong number of arguments (given: 2, expected: 0). I can get it to work by being extremely explicit with param names. For example this does work...

class Bicycle
  attr_reader :gears
  def initialize( gears: 1, 
    seats: 2, 
    wheels: 2 )
    @gears = gears
    @seats = seats
    @wheels = wheels
  end  
end  
class CrazyBicycle < Bicycle
  def initialize( seats: 2, 
    wheels: 2 )
    super(gears: 101, seats: seats, wheels:wheels)
  end  
end  

b = CrazyBicycle.new(seats: 3,wheels: 4)
puts b.gears

But that seems like a lot of unnecessary variable names. Is there some sort of Ruby sugar I can use to prevent being that explicit?

Jackie
  • 21,969
  • 32
  • 147
  • 289
  • Not directly related, but most Rubyists do not put method arguments on different lines. Yours is fine syntactically, but would be frowned upon by most Rubyists. – Kyle Heironimus Dec 14 '17 at 18:23
  • or maybe https://stackoverflow.com/a/4557470/525478, which has defaults, but a similar concept... – Brad Werth Dec 14 '17 at 18:29

2 Answers2

2

You are using keyword arguments, so must always pass the argument names when calling them. If you don't want to pass the argument name, remove the colon like so:

class Bicycle
  attr_reader :gears
  def initialize( gears = 1, 
    seats = 2, 
    wheels = 2 )
  ...
end
Kyle Heironimus
  • 7,741
  • 7
  • 39
  • 51
0

With keyword arguments you need to specify the argument name whenever that initialize method is called, even if that's indirectly via super:

class CrazyBicycle < Bicycle
  def initialize(seats: 2, wheels: 2)
    super(gears: 101, seats: seats, wheels: wheels)
  end  
end
tadman
  • 208,517
  • 23
  • 234
  • 262