Gwater17 Gwater17 - 1 year ago 58
Ruby Question

Order of methods and NoMethodError

Here's my code.

print "What's your first name"
first_name = gets.chomp.capitalize!

print "What's your last name"
last_name = gets.capitalize!.chomp

If I have
with a capitalized string (i.e
Johnson, Williams
), I get an error on the last line:

undefined method `chomp' for nil:NilClass (NoMethodError)

If I either type more capital letters, type all lowercase, or have the
method before
, the code runs fine.

Can someone explain this error?


You have to read the documentation on these very carefully to see how they work as there are often surprises. In this case capitalize! will return nil if no changes are made.

So your first version is correct:


That's also the most reasonable order of operations: You should trim your data before operating on it.

It's also worth noting that using the in-place version is not necessary as you're assigning to a variable anyway:

first_name = gets.chomp.capitalize

Given the nature of names, capitalizing might be a bad plan anyway. What about "de Lorean"?