Converting Upper-Case String into Title-Case Using Ruby

Converting upper-case string into title-case using Ruby

While trying to come up with my own method (included below for reference), I realized that there's some pretty nasty corner cases. Better just use the method already provided in Facets, the mostest awesomest Ruby library evar:

require 'facets/string/titlecase'

class String
def titleize
split(/(\W)/).map(&:capitalize).join
end
end

require 'test/unit'
class TestStringTitlecaseAndTitleize < Test::Unit::TestCase
def setup
@str = "i just saw \"twilight: new moon\", and man! it's crap."
@res = "I Just Saw \"Twilight: New Moon\", And Man! It's Crap."
end
def test_that_facets_string_titlecase_works
assert_equal @res, @str.titlecase
end
def test_that_my_own_broken_string_titleize_works
assert_equal @res, @str.titleize # FAIL
end
end

If you want something that more closely complies to typical writing style guidelines (i.e. does not capitalize words like "and"), there are a couple of "titleize" gems on GitHub.

From title case to sentence case

Try this,

"something_like_this".humanize

http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-humanize

how to use ruby/rails to convert all caps to proper first letter cap, rest lower case?

If you can separate the states out, like you say, it's easy:

my_address_string.titlecase

It'll capitalize the first letter of every word (including some I'd rather it didn't, like "a" or "the", but hey...) and uncapitalize the rest. Sounds just like what you want.

Convert UPPERCASE to Title Case

Many of the useful existing NSString methods are available from Swift. This includes capitalizedString, which may just do exactly what you want, depending on your requirements.

Simpler way to alternate upper and lower case words in a string

You could reduce the number of lines in the each_with_index block by using a ternary conditional (true/false ? value_if_true : value_if_false):

words.each.with_index do |word, i|
newstr << i.even? ? word.upcase : word.downcase
end

As for a different way altogether, you could iterate over the initial string, letter-by-letter, and then change the method when you hit a space:

def alternating_case(str)
@downcase = true
new_str = str.map { |letter| set_case(letter)}
end

def set_case(letter)
@downcase != @downcase if letter == ' '
return @downcase ? letter.downcase : letter.upcase
end


Related Topics



Leave a reply



Submit