且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Ruby 中将字符串中的第一个字母大写

更新时间:2021-11-14 22:27:53

这取决于您使用的 Ruby 版本:

It depends on which Ruby version you use:

Ruby 2.4 及更高版本:

Ruby 2.4 and higher:

它只是有效,因为 Ruby v2.4.0 支持 Unicode 大小写映射:

It just works, as since Ruby v2.4.0 supports Unicode case mapping:

"мария".capitalize #=> Мария

Ruby 2.3 及更低版本:

Ruby 2.3 and lower:

"maria".capitalize #=> "Maria"
"мария".capitalize #=> мария

问题是,它只是没有做你想要的,它输出мария而不是Мария.

The problem is, it just doesn't do what you want it to, it outputs мария instead of Мария.

如果您使用 Rails,有一个简单的解决方法:

If you're using Rails there's an easy workaround:

"мария".mb_chars.capitalize.to_s # requires ActiveSupport::Multibyte

否则,您必须安装 unicode gem 并使用它像这样:

Otherwise, you'll have to install the unicode gem and use it like this:

require 'unicode'

Unicode::capitalize("мария") #=> Мария

红宝石 1.8:

一定要使用编码魔术注释:

#!/usr/bin/env ruby

puts "мария".capitalize

给出无效的多字节字符(US-ASCII),同时:

#!/usr/bin/env ruby
#coding: utf-8

puts "мария".capitalize

工作没有错误,但也请参阅Ruby 2.3 及更低版本"部分以了解实际大小写.

works without errors, but also see the "Ruby 2.3 and lower" section for real capitalization.