tags:

views:

586

answers:

2

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".

+10  A: 

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

HanClinto
omg... i cant believe i didn't realize this myself :( tnx dude
Roman M
Very glad to hear it helped. :)
HanClinto
+5  A: 

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.

Robert Gamble