Capitalize only first character of string and leave others alone? (Rails)

Daniel O'Connor picture Daniel O'Connor · Apr 15, 2010 · Viewed 103.8k times · Source

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

Answer

Pascal Van Hecke picture Pascal Van Hecke · Aug 22, 2011

This should do it:

title = "test test"     
title[0] = title[0].capitalize
puts title # "Test test"