Raulvv
Raulvv

Reputation: 29

Ruby - Wrong number of argument (1/2)

The question is that when I tried with a Product it works, but with a Fruit doesn´t and came this error:

shoppingCart.rb:7:in `initialize': wrong number of arguments (1 for 2) (Argument
Error)
        from shoppingCart.rb:21:in `initialize'
        from shoppingCart.rb:37:in `new'
        from shoppingCart.rb:37:in `<main>'

Code:

class Product
  attr_accessor :name
  attr_accessor :price
  attr_accessor :discount


  def initialize(name, price)
    @name = name
    @price = price
  end

  def calculatePrice
    puts "The price of the #{@name} is #{@price} euros"
  end

end

class Fruit < Product

  def initialize(name, price)
    super(name)
    super(price)
  end

  def discount()
    @discount = 10
  end
end

banana = Fruit.new("banana", 10)
banana.calculatePrice

Upvotes: 0

Views: 143

Answers (2)

Mark Reed
Mark Reed

Reputation: 95252

When you call super from Fruit#initialize, it's calling Product#initialize, which takes two arguments. So call it once with both arguments, instead of once each:

super(name, price)

Since those are the same arguments that Fruit#initialize itself takes, you can also just leave them off to automatically pass along the same ones:

super

But since you aren't doing anything Fruit-specific in Fruit#initialize, you can delete that method entirely to get the same result:

class Product 
  def initialize(name, price)
     puts "Into Product#Initialize"
  end
end

class Fruit < Product
end

banana = Fruit.new(banana, 10)
# Into Product#Initialize
# => #<Fruit:0x007f9da91cef00>

Upvotes: 2

Marek Lipka
Marek Lipka

Reputation: 51151

You have an error because you call super with one argument in Fruit#initialize, but Product#initialize takes two arguments. Since you don't do anything specific to Fruit in Fruit#initialize method, you don't need this method at all.

Upvotes: 3

Related Questions