0

The capitalize and capitalize! method

Hi everyone! I just have a question about the usage of .capitalize method. Being more precise, about it's usage in an input, just like: print "What's your name?" name=gets.chop.capitalize I have tested in this way and just works perfectly, but then I knew about the .capitalize! print "What's your name?" name=gets.chop.capitalize! And I just realized that if I write in the input the words already capitalized, they simply don't return the word, the field appears blank. I get it that .capitalize! change the variable so then I'll not need to every time capitalize it when I need to print or something like that. But I don't get this kind of "bug". I don't know even if it's a bug, but really make me stop e think and I would really apreciate some help. Thank you already.

19th Jan 2017, 2:18 AM
Hudson Monteiro
Hudson Monteiro - avatar
2 Antworten
+ 5
Indeed "capitalize!" returns nil (a.k.a null) if no changes were made. Check if the word is already capitalized or .capitalize if is different than nil.
19th Jan 2017, 5:24 AM
Nahuel
Nahuel - avatar
+ 3
In Ruby, convention tell that a function with exclamation dot ( ! ) append to it, is the version which modify the argument while the not appended version modify a copy and return it... So: text='this is a sample text' print text.capialize # output: This is a sample text print text # output: this is a sample text text.capitalize! print text # output: This is a sample text
19th Jan 2017, 5:57 AM
visph
visph - avatar