Search code examples
rubyloopsrubymine

possible undefined local variable for loop condition


Rubymine flags the variable found as potentially undefined. I thought the answer would be to move the variable found outside the begin but I then go into a tight loop that never exits. I am sure this is a block scoping issue but lack the ruby experience to realise what the issue is. I am assuming that this is being flagged because found is declared inside the begin, so the question here is.. is this valid code or is Rubymine's inspector wrong in this instance ?

begin
  found = false
  @some_collection.keys.each do |key|
    found = evaluate_collection(@some_collection[key], key) unless found
  end
end while found

Solution

  • According to the rubyspec for while:

     it "executes code in containing variable scope" do
        i = 0
        while i != 1
          a = 123
          i = 1
        end
    
        a.should == 123
      end
    

    As begin...end while bool is just another form of a while statement, it also executes in the containing variable scope:

    begin
      found = 'asdf'
    end while false
    puts found
    

    Will output asdf