RomanM
RomanM

Reputation: 6711

Ruby 'Capitalize!' paradox

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

Upvotes: 7

Views: 2360

Answers (2)

HanClinto
HanClinto

Reputation: 9461

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

Upvotes: 17

Robert Gamble
Robert Gamble

Reputation: 109012

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.

Upvotes: 7

Related Questions