Add two method to string class to capitalize first letter : capitalize « String « Ruby






Add two method to string class to capitalize first letter


class String
  def capitalize_first_letter
    self[0].chr.capitalize + self[1, size]
  end

  def capitalize_first_letter!
    unless self[0] == (c = self[0,1].upcase[0])
      self[0] = c
      self
    end
  end
end

s = 'this is a test'
puts s 
puts s.capitalize_first_letter   
puts s                           
puts s.capitalize_first_letter!
puts s                           

 








Related examples in the same category

1.Capitalize the result with the capitalize method, if you want
2.Call capitalize function from string class