Skip to content

Potentially uninitialized local variable #2845

@bjormgyg

Description

@bjormgyg

In Ruby, it is not necessary to explicitly initialize variables. If a local variable has not been explicitly initialized, it will have the value nil. If this happens unintentionally, though, the variable will not represent an object with the expected methods, and a method call on the variable will raise a NoMethodError.

In the following code, the call to create_file may fail and then the call f.close will raise a NoMethodError since f will be nil at that point.

def dump(x)
  f = create_file
  f.puts(x)
ensure
  f.close
end

References

Everything You Need To Know About Nil
NoMethodError

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions