开发者

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

Or it seems like I have to write my own method? (to keep the DHA untouched):

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)" 


My apologies if my answer is just rubbish (I don't do ruby). But I believe I've found an answer for you:

Ruby equivalent of PHP's ucfirst() function


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

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

[Oh... but that's overly complicated if you just want the first character of the string... the gsub will do the first character of each word. s[0] = s[0].upcase would work just fine.]


You can use .titleize or .titlecase for capitalize the first letter of the word.

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

Or you can use

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


Ruby doesn't have a method with the exact behavior you're looking for.


Personally, for simple uses like this, I'd use:

s[0] = s[0].upcase


Rails 5 added this; it's called upcase_first.

In Rails 4 or before, add this to a string extension.

class String

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

end


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


.humanize comes close, but it downcaseses the rest of the string. I think the Tin Man's answer is the simplest.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜