C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: We try to locate a value that is not present. And the index method returns nil.
ArrayCaution: We must test for nil before calling methods on an object. This is shown in the example after this one.
Ruby program that uses nil
# An array of three elements.
values = Array[10, 30, 50]
# Try to find an element that does not exist.
if values.index(70) == nil
# This is reached.
puts "Result is nil"
end
Output
Result is nil
Not found: In this example, we access an element in a Hash that is not found. The Hash lookup returns a nil object.
HashThen: We try to use that object as though it were a string. But calling length() on nil is not possible.
StringTip: Try changing the hash["b"] lookup to use instead the key "a". The program will proceed without an error. The key exists.
Ruby program that causes NoMethodError
# An example hash.
hash = Hash["a" => "dog"]
# Get an element that does not exist.
v = hash["b"]
# We cannot use length on it.
puts v.length()
Output
...undefined method 'length' for nil:NilClass (NoMethodError)
Note: Any variable can be assigned nil manually, as with assignment. So nil is not just for uninitialized variables.
Ruby program that shows nil field
class Box
def size
@value
end
end
# Create a new class instance.
x = Box.new
# A field on a class is nil until initialized.
if x.size == nil
puts "NIL"
end
Output
NIL
Ruby program that has method, returns nil
def analyze(n)
# This method returns nil unless n equals 2.
if n == 2
return n * 2
end
end
puts "Result is nil" if analyze(3) == nil
Output
Result is nil