使用 Ruby 将大写字符串转换为标题大小写

编程入门 行业动态 更新时间:2024-10-27 06:31:51
本文介绍了使用 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 将大写字符串转换为标题大小写

本文发布于:2023-11-12 11:33:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581388.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:大小写   字符串   转换为   标题   Ruby

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!