Ruby 相当于 PHP 的 ucfirst() 函数 [英] Ruby equivalent of PHP's ucfirst() function

查看:61
本文介绍了Ruby 相当于 PHP 的 ucfirst() 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby(使用 Rails,如果相关)中将字符串的第一个字母大写的最佳方法是什么?

What's the best way in Ruby (with Rails, if relevant) to capitalize the first letter of a string?

请注意,String#capitalize 不是我想要的,因为除了将字符串的第一个字母大写外,该函数还使所有其他字符小写(我不想要 - 我想让它们保持原样):

Note that String#capitalize is not what I want since, in addition to capitalizing the first letter of the string, this function makes all other characters lowercase (which I don't want -- I'd like to leave them untouched):

>> "a A".capitalize
=> "A a"

推荐答案

你可以使用sub"来获得你想要的(注意:我没有用多字节字符串测试过这个)

You can use "sub" to get what you want (note: I haven't tested this with multibyte strings)

"a A".sub(/^(\w)/) {|s| s.capitalize}

(如果您愿意,您当然可以使用monkeypatch String 将其添加为方法)

(and you can of course monkeypatch String to add this as a method if you like)

这篇关于Ruby 相当于 PHP 的 ucfirst() 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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