7

In Ruby we have the 'bang' method capitalize! which has the strange behavior of returning a nil if no changes to the string were made.

That means I can't chain this commands with other since it effectively destroys the chain if it returns nil.

What im trying to do is something like this:

fname =  fullname[0...fullname.index(' ')].capitalize!

which extracts the first name from a string and should capitalize it as well. But if it is already capitalized the string stored in fname is nil.

Of courses I can add another statement but was wondering if there is a way to do this "without breaking the chain".

2 Answers 2

17

Use .capitalize (without the bang) -- unless you actually need it to change the source.

3
  • omg... i cant believe i didn't realize this myself :( tnx dude
    – RomanM
    Nov 19, 2008 at 23:54
  • Very glad to hear it helped. :)
    – HanClinto
    Nov 20, 2008 at 0:00
  • @HanClinto What if you need the variable to capitalize and save (via !) but can not guarantee the user will input in lowercase? Is there a way to do this without chaining another method?
    – FluxEngine
    Jan 2, 2013 at 19:15
7

Since your statement doesn't change the value of fullname, just do:

fname =  fullname[0...fullname.index(' ')].capitalize

Which doesn't return nil if no change is made.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.