Ruby/String/capitalize

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

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



Call capitalize function from string class

"Test".capitalize



Capitalize the result with the capitalize method, if you want

line = "A horse! a horse! my kingdom for a horse!"
line[18, 23].capitalize # => "My kingdom for a horse!"