Ruby forgets local variables during a while loop?

后端 未结 6 826
我在风中等你
我在风中等你 2020-12-09 17:07

I\'m processing a record-based text file: so I\'m looking for a starting string which constitutes the start of a record: there is no end-of-record marker, so I use the start

6条回答
  •  情书的邮戳
    2020-12-09 17:45

    I'm not sure why you're surprised: on line 5 (assuming that the message = nil line isn't there), you potentially use a variable that the interpreter has never heard of before. The interpreter says "What's message? It's not a method I know, it's not a variable I know, it's not a keyword..." and then you get an error message.

    Here's a simpler example to show you what I mean:

    while line = gets do
      if line =~ /./ then
        puts message # How could this work?
        message = line
      end
    end
    

    Which gives:

    telemachus ~ $ ruby test.rb < huh 
    test.rb:3:in `
    ': undefined local variable or method `message' for main:Object (NameError)

    Also, if you want to prepare the way for message, I would initialize it as message = '', so that it's a string (rather than nil). Otherwise, if your first line doesn't match hello, you end up tring to add line to nil - which will get you this error:

    telemachus ~ $ ruby test.rb < huh 
    test.rb:4:in `
    ': undefined method `<<' for nil:NilClass (NoMethodError)

提交回复
热议问题