使用 Ruby 将大写字符串转换为标题大小写 [英] Converting upper-case string into title-case using Ruby

查看:42
本文介绍了使用 Ruby 将大写字符串转换为标题大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 Ruby 中的全大写字符串转换为小写字符串,但每个单词的第一个字符都是大写.示例:

I'm trying to convert an all-uppercase string in Ruby into a lower case one, but with each word's first character being upper case. Example:

将我的字符串"转换为我的字符串".

convert "MY STRING HERE" to "My String Here".

我知道我可以使用 .downcase 方法,但这会使所有内容都小写(我的字符串在这里").我正在扫描文件中的所有行并进行此更改,那么是否有可以通过 ruby​​ 使用的正则表达式来实现此目的?

I know I can use the .downcase method, but that would make everything lower case ("my string here"). I'm scanning all lines in a file and doing this change, so is there a regular expression I can use through ruby to achieve this?

谢谢!

推荐答案

在尝试提出我自己的方法(包含在下面以供参考)时,我意识到有一些非常讨厌的极端情况.最好使用 Facets 中已经提供的方法,这是最棒的 Ruby 库 evar:

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

如果您想要一些更符合典型写作风格指南的内容(即不将and"之类的单词大写),GitHub 上有几个titleize" gems.

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.

这篇关于使用 Ruby 将大写字符串转换为标题大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆