我在同一个目录中有两个文件rabbit.rb和main01.rb,当我运行main01.rb时,我得到这个错误消息
`“:未初始化的常量Rabbit(NameError)
我做错了什么谢谢你的帮助。
兔子.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

最佳答案

您可以使用require "./rabbit"而不是require_relative "rabbit"
您还引用了main01.rb末尾变量名错误的数组尝试:

rabbits[0].name = "wooser"
puts rabbits[0].name

关于ruby - `<main>':未初始化的常量Rabbit(NameError),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27538184/

10-13 01:59