我试图让Rails将字符串的第一个字符大写,并让其他所有字符保持原样.我遇到了一个问题,"我来自纽约"变成了"我来自纽约"
我将使用什么方法 Select 第一个字符?
谢谢
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. 谢谢 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. 谢谢 for the help!
等等,不,我没有...我的模特名单上有什么.
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:人try 了梅塞克的编辑,但仍然得到了undefined method `capitalize'"个错误.我可能做错了什么?
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
这太奇怪了.通过使用下面的行,我能够消除未定义的方法错误.问题是它似乎用数字代替了第一个字母.例如,它不是将You中的y大写,而是将y变成121
self.title[0] = title[0].to_s.capitalize