我正在尝试将Ruby中的全大写字符串转换为小写字符串,但每个单词的第一个字符都是大写的。示例:
将"MY STRING Here“转换为"My String HERE”。
我知道我可以使用.downcase方法,但这会使所有内容都变得小写(“这里是我的字符串”)。我正在扫描文件中的所有行并进行此更改,那么有没有一个正则表达式可以通过ruby来实现这一点?
谢谢!
发布于 2009-11-25 02:48:14
当我试图想出我自己的方法(包含在下面以供参考)时,我意识到有一些非常糟糕的角落案例。最好使用Facets中已经提供的方法,最棒的Ruby库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如果你想要更符合典型写作风格的东西(也就是不大写“and”之类的单词),GitHub上有几个“标题化”的宝石。
发布于 2009-11-25 02:15:37
如果您正在使用Rails (实际上您所需要的就是ActiveSupport,它是Rails的一部分),那么您可以使用titleize
"MY STRING HERE".titleize
# => "My String Here"如果你正在使用普通的Ruby,但是不介意加载少量的ActiveSupport,你可以首先需要它:
require 'active_support/core_ext/string/inflections'
# => true
"MY STRING HERE".titleize
# => "My String Here"N.B.默认情况下,titleize不能很好地处理首字母缩写,它会将camelCaseStrings拆分成单独的单词。这可能是也可能不是我们想要的:
"Always use SSL on your iPhone".titleize
# => "Always Use Ssl On Your I Phone"你可以(部分地)通过添加“acronyms”来解决这个问题:
require 'active_support/core_ext/string/inflections' # If not using Rails
ActiveSupport::Inflector.inflections do |inflect|
inflect.acronym 'SSL'
inflect.acronym 'iPhone'
end
"Always use SSL on your iPhone".titleize
# => "Always Use SSL On Your IPhone"对于那些说女王英语的人(或者拼写.titleise的人),没有titleize的别名,但你可以用.titlecase代替。
发布于 2009-11-25 01:33:19
"HELLO WORLD HOW ARE YOU".gsub(/\w+/) do |word|
word.capitalize
end
#=> "Hello World How Are You"https://stackoverflow.com/questions/1791639
复制相似问题