Rails 5: New upcase_first Method

Have you ever needed to capitalize just the first letter of a String in Ruby/Rails?

Very likely you tried something like that, no?!

"hello John".capitalize
=> "Hello john"

But the result is not the expected one..

That's why String#capitalize converts the first character to uppercase and all others to lowercase.

We can resolve it simply with sub(/\S/, &:upcase) or any other implementation:

"hello John".sub(/\S/, &:upcase)
=> "Hello John"

But it is a bit verbose. I wouldn't like to have to call such method whenever I need to capitalize just the first character..

We can add a new method to the String class as well (and put it into a Rails initializer):

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

"hello John".upcase_first
=> "Hello John"

But how it seemed to be a very common need, I opened a PR and it got merged into Rails.

So, as of Rails 5.0.0.beta4 you can use the new String#upcase_first method or in its ActiveSupport version ActiveSupport::Inflector#upcase_first:

"hello John".upcase_first
=> "Hello John"

ActiveSupport::Inflector.upcase_first("hello John")
=> "Hello John"

See you.

Written on May 19, 2016

Share: