我尝试使用push将对象添加到数组中。我有一个程序,你可以注册客人。当我从菜单中选择签入选项时,无法将新访客添加到访客历史记录中。
这不起作用:
def self.check_in
puts "Welcome to the checkin"
puts "Please state your first name: "
firstName = gets.chomp
puts "Please state your last name:"
lastName = gets.chomp
puts "Write your address: "
address = gets.chomp
puts "and your phone number: "
phone = gets.chomp
puts "finally, your arrival date!"
arrived = gets.chomp
newPLot = $camping.generateParkingLot
guest = Guest.new(firstName, lastName, address, phone, arrived)
$camping.current_guests[newPLot-1] = guest
puts "The registration was a success!! You have received plot " + newPLot.to_s + "."
@all_guests.push(guest) # adds the guest to the history
end
这里我得到一个check_in': undefined method
推送nil:NilClass(NoMethodError)。但如果我注释掉这一行:
#@all_guests.push(guest) # adds the guest to the history
我可以注册一位客人。然后,当我从菜单中选择3选项时:
def self.do_action(action)
# utför händelse baserat på valet
case action
when 1:
check_in
when 2:
check_out
when 3:
puts $camping.current_guests
when 4:
puts $camping.all_guests
when 5:
puts "You are now leaving the camping, welcome back!"
exit
end
end
然后我看到那里的客人。唯一的问题是我不能做4显示所有客人的选项,因为我已经注释掉了这行代码。因此,为了解决这个问题:
@all_guests.push(guest) # adds the guest to the history
没有收到错误消息??感谢所有的帮助!
答案 0 :(得分:4)
@all_guests
未在您收到错误的文件中定义,它在$camping
全局中定义。将代码更改为
$camping.all_guests.push(...)
并查看这是否适合您。