Home
Search
Nil Value Examples: NoMethodErrorTest values against nil, with an if, to avoid errors like NoMethodError.
Ruby
This page was last reviewed on Oct 1, 2022.
Nil. In Ruby, nil is a special value. It indicates a value that is not present. Methods often return nil when they attempt to locate an element that does not exist.
We must check for nil in many locations in our code. Uninitialized fields in classes are nil too. Nil is everywhere: without nothing, there cannot be something.
if
First example. This example shows how nil is used with the Array class. We create an array with 3 integer elements. We then call the index method on the array.
And We try to locate a value that is not present. And the index method returns nil.
Array
Warning We must test for nil before calling methods on an object. This is shown in the example after this one.
# 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
Result is nil
NoMethodError. We cannot call methods on the nil object. This will cause a NoMethodError. And at this point, program execution ceases. We must first test references to see if they are nil.
Not found In this example, we access an element in a Hash that is not found. The Hash lookup returns a nil object.
Hash
Then We try to use that object as though it were a string. But calling length() on nil is not possible.
Tip Try changing the hash["b"] lookup to use instead the key "a". The program will proceed without an error. The key exists.
# 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()
...undefined method 'length' for nil:NilClass (NoMethodError)
Uninitialized fields. A field in a class is automatically set to nil before it is assigned a value. So we can check for nil to see if a field has been initialized yet.
Class
Note Any variable can be assigned nil manually, as with assignment. So nil is not just for uninitialized variables.
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
NIL
Return nil. Methods return nil if no other return value is specified. Often, nil is returned when no value can be found. Here, analyze() returns nil unless "n" equals 2.
Methods
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
Result is nil
A review. Any class in Ruby can be nil. If our program logic can possibly result in a nil object, we must first test for nil to prevent errors.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 1, 2022 (edit).
Home
© 2007-2022 sam allen.
see site info on the changelog.