dez82
dez82

Reputation: 21

Strings being emptied by capitalize! when user enters input with correct formatting

I am working through some exercises at the moment.

I have written the following code

print "What's your first name?"
first_name=gets.chomp.capitalize!
print "Last name"
last_name=gets.chomp.capitalize!
print "City"
city=gets.chomp.capitalize!
print "State(Caps)"
state=gets.chomp.upcase!
print "Your name is #{first_name} #{last_name} from #{city}, #{state}"

When I use incorrect formatting for input (eg. john or nEW yORK, the routine runs fine.

However, if everything entered = the correct output, ie. John or New York, the routine empties the corresponding string variable.

Is there a way to ignore the capitalize! method if the input is correctly formatted?

Upvotes: 2

Views: 375

Answers (3)

Ian Stapleton Cordasco
Ian Stapleton Cordasco

Reputation: 28757

Everyone here is giving you the reason why you get nil and the solution but I see no explanations of the difference between the methods you're using.

Every function and method in Ruby returns a value and sometimes there are two versions of the same method. One version usually returns a new object without modifying the original while the other modifies the original and may (or may not) return the changed value.

The latter type is almost always suffixed by an !. So what your code is doing is:

  • get input from the user and store it as a string
  • create a new string, remove the \n and return it
  • capitalize the new string and modify itself

So the last object created is modified if needed and not returned because there's no reason to return that. Just like there is a capitalize! method on Strings, there is also a chomp! method. Imagine if instead if there were no \n at the end of the string returned from gets. Then chomp! would return nil and nil.capitalize would throw an exception.

If you change your code to just use capitalize as everyone else rightly tells you to, the execution will look like this:

  • get input from the user and store it as a string
  • create a new string, remove the \n and return it
  • create a new string, capitalize it and return it

Upvotes: 1

brymck
brymck

Reputation: 7663

capitalize! returns a capitalized string if it's not capitalized, and nil if there's nothing to capitalize (i.e. before and after are the same). See String#capitalize!. There are other methods like this for strings, like gsub!, that return nil if the in-place edit does nothing.

Just use capitalize instead.

Upvotes: 1

Benjamin Tan Wei Hao
Benjamin Tan Wei Hao

Reputation: 9691

Try capitalize instead of the one with the "!". The version with the bang returns nil when nothing is changed. Docs here.

Upvotes: 6

Related Questions