Does Ruby or Rails have a method to use only the first character?

Or does it seem to me that I should write my own method? (to keep DHAintact):

ruby-1.9.2-p180 :001 > s = 'omega-3 (DHA)'
 => "omega-3 (DHA)" 

ruby-1.9.2-p180 :002 > s.capitalize
 => "Omega-3 (dha)" 

ruby-1.9.2-p180 :003 > s.titleize
 => "Omega 3 (Dha)" 

ruby-1.9.2-p180 :005 > s[0].upcase + s[1..-1]
 => "Omega-3 (DHA)" 
+5
source share
8 answers

My apologies if my answer is just rubbish (I do not make ruby). But I believe that I have found the answer for you:

Ruby equivalent of ucfirst () PHP function

+4
source

You can use gsub with a regular expression that matches the first character of each word and replaces it with an uppercase character:

ruby-1.9.2-p180 :001 > 'omega-3 (DHA)'.gsub(/\b\w/){ $&.upcase }
 => "Omega-3 (DHA)" 

[... , ... gsub . s[0] = s[0].upcase .]

+4

.titleize .titlecase .

: - "manish anand" .titleize = > "manish anand" .titlecase = > Manish Anand

"manish anand" .split.map(&: capize).join('') = > Manish Anand

+3

Ruby , .

+2

, , :

s[0] = s[0].upcase
+2

Ruby does not have a method to fill in only the first character (and leave all the other letters alone). You should use your own solution as your fourth example.

0
source

.humanize comes close, but it crosses out the rest of the line. I think the tin answer is the simplest.

s[0] = s[0].upcase
0
source

Rails 5 added this; he is called upcase_first.

In Rails 4 or earlier, add this to the line extension.

class String

  def upcase_first
    self.sub(/\S/, &:upcase)
  end

end
0
source

All Articles