Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby 'Capitalize!' paradox

Tags:

ruby

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

like image 853
RomanM Avatar asked Nov 19 '08 23:11

RomanM


1 Answers

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

like image 125
HanClinto Avatar answered Sep 16 '22 17:09

HanClinto