【问题标题】:undefined method `push' for nil:NilClass (NoMethodError) Rubynil:NilClass (NoMethodError) Ruby 的未定义方法“push”
【发布时间】:2010-08-03 19:11:17
【问题描述】:

我正在尝试使用 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 methodpush' 表示 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 

没有收到错误信息??感谢所有帮助!

【问题讨论】:

  • 一旦第一个问题得到回答,请勿编辑您的问题以将其更改为完全不同的问题。我将对其进行编辑以还原您的更改。问第二个问题。 (如果你害怕在 StackOverflow 上问太多问题——我们可能不会友好地为你调试整个程序——找一个你可以亲自问的知识渊博的人。)
  • 我真的很抱歉。这是我第一次实际使用 StackOverflow 来处理这些事情,所以我是新手。所以这与我害怕提出新问题无关,只是因为我认为我可以那样做。

标签: ruby arrays


【解决方案1】:

@all_guests 未在您收到错误的文件中定义,它在 $camping 全局中定义。把代码改成

$camping.all_guests.push(...)

看看这是否更适合你。

【讨论】:

  • 该死!谢谢!!令人难以置信的是,我已经在那个问题上挣扎了多久。我欠你的:)
  • 不客气。如果这解决了您的问题,您介意接受答案吗?
猜你喜欢
  • 1970-01-01
  • 2023-03-06
  • 2016-06-15
  • 2013-02-17
  • 2014-03-16
  • 1970-01-01
  • 1970-01-01
  • 2013-11-14
  • 2013-01-14
相关资源
最近更新 更多