Ruby类初始化报错:new方法参数数量不匹配(给定7,预期0)
问题原因及修复方案
核心错误1:attr_accessor行末尾多余逗号
你代码里的attr_accessor声明最后多了一个逗号:
attr_accessor :id, :firstname, :secondname, :club, :position, :price, :totalpoints,
这个多余的逗号会让Ruby解析器误以为你还在给attr_accessor传递参数,后续的def initialize会被错误地解析为attr_accessor的参数之一,导致你的自定义initialize方法根本没有被正确定义为类的实例方法。此时Ruby会使用默认的无参数initialize方法,所以调用Quarterback.new传入7个参数时就会触发ArgumentError。
核心错误2:实例化代码放在类定义内部
你把sparky = Quarterback.new(...)和puts sparky.info写在了Quarterback类的内部(end之前),这不符合Ruby语法规范,类内部只能定义方法、常量等,实例化代码应该放在类定义之外。
修正后的完整代码
class Quarterback attr_accessor :id, :firstname, :secondname, :club, :position, :price, :totalpoints def initialize(id, firstname, secondname, club, position, price, totalpoints) @id = id @firstname = firstname @secondname = secondname @club = club @position = position @price = price @totalpoints = totalpoints end def info "#{firstname} works for #{club} and has a cost of #{price}." end end # 实例化代码放在类定义外部 sparky = Quarterback.new('1', 'John', 'Edgar', 'Liverpool', 'Forward', '100', '38') puts sparky.info
运行修正后的代码,会正常输出预期结果:John works for Liverpool and has a cost of 100.
内容的提问来源于stack exchange,提问作者ldthompson
相关产品推荐
相关产品推荐

