[英]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: 问题是,当我尝试使用Product时,它可以工作,但是使用Fruit时,却没有出现此错误:
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
You have an error because you call super
with one argument in Fruit#initialize
, but Product#initialize
takes two arguments. 您有一个错误,因为您在
Fruit#initialize
使用一个参数调用了super
,但是Product#initialize
接受了两个参数。 Since you don't do anything specific to Fruit
in Fruit#initialize
method, you don't need this method at all. 由于您在
Fruit#initialize
方法中不执行任何特定于Fruit
操作,因此根本不需要此方法。
When you call super
from Fruit#initialize
, it's calling Product#initialize
, which takes two arguments. 当您从
Fruit#initialize
调用super
,它将调用Product#initialize
,该方法带有两个参数。 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: 由于这些参数与
Fruit#initialize
本身采用的参数相同,因此您也可以将其保留为自动传递相同的参数:
super
But since you aren't doing anything Fruit
-specific in Fruit#initialize
, you can delete that method entirely to get the same result: 但因为你没有做任何事情
Fruit
中特异性Fruit#initialize
,您可以删除方法完全得到相同的结果:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.