我在同一目录下有两个文件rabbit.rb和main01.rb,当我运行main01.rb时,收到此错误信息
`':未初始化的常量Rabbit(NameError)
我做错了什么?谢谢你的帮助。
rabbit.rb
class Rabbit
attr_accessor :name
attr_reader :color, :length_of_ears
def initialize(name: "usachan", color: :white, length_of_ears: 10)
@name = name
@color = color
@length_of_ears = length_of_ears
end
def jump
puts "pyon! pyon!"
end
def pound_steamed_rice_into_rice_cake
puts "pettan! pettan!"
end
def say_name
puts "Hello, I'm #{name}!"
end
end
main01.rb
require_relative "rabbit"
rabbits = []
rabbits.push(Rabbit.new)
rabbits.push(Rabbit.new(name: "pyonkichi"))
rabbits.push(Rabbit.new(name: "inaba", color: :brown, length_of_ears: 7))
rabbits.each do |rabbit|
puts rabbit.name
puts rabbit.color
puts rabbit.length_of_ears
rabbit.say_name
puts ""
end
rabbit[0].name = "wooser"
puts rabbit[0].name
答案 0 :(得分:0)
您可以使用require "./rabbit"
代替require_relative "rabbit"
您还指的是main01.rb
末尾带有错误变量名的数组。尝试:
rabbits[0].name = "wooser"
puts rabbits[0].name