Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Potentially uninitialized local variable

ID: rb/uninitialized-local-variableKind: problemSecurity severity: Severity: errorPrecision: highTags:   - quality   - reliability   - correctnessQuery suites:   - ruby-security-and-quality.qls

Click to see the query in the CodeQL repository

Overview

In Ruby, it is not necessary to explicitly initialize variables.If a local variable has not been explicitly initialized, it will have the valuenil. 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 aNoMethodError.

Recommendation

Ensure that the variable cannot benil at the point highlighted by the alert.This can be achieved by using a safe navigation or adding a check fornil.

Note: You do not need to explicitly initialize the variable, if you can make the program deal with the possiblenil value. In particular, initializing the variable tonil will have no effect, as this is already the value of the variable. Ifnil is the only possible default value, you need to handle thenil value instead of initializing the variable.

Example

Incorrect Usage

In the following code, the call tocreate_file may fail and then the callf.close will raise aNoMethodError sincef will benil at that point.

defdump(x)f=create_filef.puts(x)ensuref.closeend

Correct Usage

We can fix this by using safe navigation:

defdump(x)f=create_filef.puts(x)ensuref&.closeend

References


[8]ページ先頭

©2009-2025 Movatter.jp