concept nomethoderror in category ruby

This is an excerpt from Manning's book The Well-Grounded Rubyist, Third Edition.
Whenever Ruby encounters NoMethodError, did_you_mean kicks in with one or more suggestions of a method you might have meant to call instead of the one you did call. The format is always the same: the words “Did you mean?” followed by a valid Ruby method. did_you_mean is most frequently helpful when you’ve made a simple typo, suggesting the correctly spelled method name and potentially saving you some time digging around for the error.
Table 6.1. Common exceptions (view table figure)
Exception name
Common reason(s)
How to raise it
RuntimeError The default exception raised by the raise method. raise NoMethodError An object is sent a message it can’t resolve to a method name; the default method_missing raises this exception. a = Object.new a.some_unknown_method_name NameError The interpreter hits an identifier it can’t resolve as a variable or method name. a = some_random_identifier IOError Caused by reading a closed stream, writing to a read-only stream, and similar operations. STDIN.puts("Don't write to STDIN!") Errno::error A family of errors relates to file I/O. File.open(-12) TypeError A method receives an argument it can’t handle. a = 3 + "can't add a string to a number!" ArgumentError Caused by using the wrong number of arguments. def m(x); end; m(1,2,3,4,5)
One of the most common exceptions in Ruby is NoMethodError. As you already know, no mechanism exists to prevent you from calling methods that either don’t exist or that have yet to be defined in an object’s scope. Anytime this happens, Ruby will throw a NoMethodError at runtime. In chapter 1 we looked at the did_you_mean? gem and its power to help quickly diagnose these errors.
Another common cause of NoMethodError exceptions is when methods are unintentionally called on nil. This is where the safe navigation operator, &., can help us. To demonstrate, let’s construct a Roster object for a sports team. The Roster will contain multiple Player objects.
tourney_roster2 hasn’t yet been set with any players. The preceding code will raise a NoMethodError because tourney_roster2.players returns nil. We can add conditional statements to avoid this, but it makes our if statement verbose and unclear:
if tourney_roster2.players && tourney_roster2.players.first && tourney_roster2.players.first.position == "Forward"Instead, we can use the safe navigation operator to avoid the NoMethodError: