Note that there are some explanatory texts on larger screens.

plurals
  1. POCapitalize only first character of string and leave others alone? (Rails)
    primarykey
    data
    text
    <p>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." </p> <p>What method would I use to select the first character?</p> <p>Thanks </p> <p><strong>EDIT:</strong> I tried to implement what macek suggested, but I'm getting a <em>"undefined method `capitalize'"</em> error. The code works fine without the capitalize line. Thanks for the help!</p> <pre><code>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 </code></pre> <p><strong>EDIT 2:</strong> Got it working. Thanks for the help!</p> <p><strong>EDIT 3:</strong> Wait, no I didn't... Here's what I have in my list model.</p> <pre><code>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 </code></pre> <p><strong>EDIT 4:</strong> Tried macek's edit, and still getting an <em>undefined method `capitalize'"</em> error. What could I be doing wrong?</p> <pre><code>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 </code></pre> <p><strong>EDIT 5:</strong> 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 <em>y</em> in <em>You</em>, it turns the <em>y</em> into a 121 </p> <pre><code>self.title[0] = title[0].to_s.capitalize </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload