问题描述
upcase
方法将整个字符串大写,但我只需要将第一个字母大写.
The upcase
method capitalizes the entire string, but I need to capitalize only the first letter.
此外,我需要支持多种流行语言,例如德语和俄语.
Also, I need to support several popular languages, like German and Russian.
我该怎么做?
推荐答案
这取决于您使用的 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.
这篇关于如何在 Ruby 中将字符串中的第一个字母大写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!