I'm trying to get Rails to capitalize the first character of a string, and leave all the others the way they are. I'm running into a problem where "i'm from New York" gets turned into "I'm from new york."
What method would I use to select the first character?
Thanks
EDIT: I tried to implement what macek suggested, but I'm getting a "undefined method `capitalize'" error. The code works fine without the capitalize line. Thanks for the help!
def fixlistname! self.title = self.title.lstrip + (title.ends_with?("...") ? "" : "...") self.title[0] = self.title[0].capitalize errors.add_to_base("Title must start with \"You know you...\"") unless self.title.starts_with? 'You know you' end EDIT 2: Got it working. Thanks for the help!
EDIT 3: Wait, no I didn't... Here's what I have in my list model.
def fixlistname! self.title = self.title.lstrip + (title.ends_with?("...") ? "" : "...") self.title.slice(0,1).capitalize + self.title.slice(1..-1) errors.add_to_base("Title must start with \"You know you...\"") unless self.title.starts_with? 'You know you' end EDIT 4: Tried macek's edit, and still getting an undefined method `capitalize'" error. What could I be doing wrong?
def fixlistname! self.title = title.lstrip self.title += '...' unless title.ends_with?('...') self.title[0] = title[0].capitalize errors.add_to_base('Title must start with "You know you..."') unless title.starts_with?("You know you") end EDIT 5: This is weird. I'm able to get rid of the undefined method error by using the line below. The problem is that it seems to replace the first letter with a number. For example, instead of capitalizing the y in You, it turns the y into a 121
self.title[0] = title[0].to_s.capitalize
EDIT 3, you need to start line 2 withself.title =. Also, on all 3 lines, you only needself.titleon the left of an=(equal sign). In other places you can just usetitle. See the edit on my answer for an example.upcase_first< answer there for anyone using Rails 5+. Credit @user1519240. Would be a good accepted answer if @DanielOConnor ever revisits this :)