如何在Ruby中將字符串轉換爲小寫或大寫

如何在Ruby中將字符串轉換爲小寫或大寫? html


#1樓

ruby downcase方法返回一個字符串,其大寫字母替換爲小寫字母。 api

"string".downcase

https://ruby-doc.org/core-2.1.0/String.html#method-i-downcase ruby


#2樓

Ruby有幾種更改字符串大小寫的方法。 要轉換爲小寫,請使用downcaseui

"hello James!".downcase    #=> "hello james!"

一樣, upcase字母將每一個字母capitalizecapitalize字母將第一個字母大寫,其他字母小寫: spa

"hello James!".upcase      #=> "HELLO JAMES!"
"hello James!".capitalize  #=> "Hello james!"
"hello James!".titleize    #=> "Hello James!"

若是要在適當位置修改字符串,則能夠將驚歎號添加到如下任何方法中: code

string = "hello James!"
string.downcase!
string   #=> "hello james!"

有關更多信息,請參考String文檔htm


#3樓

...,大寫爲: 對象

"Awesome String".upcase
=> "AWESOME STRING"

#4樓

您能夠經過打開irb並運行如下命令來找到String上可用的全部方法: unicode

"MyString".methods.sort

並特別列出了可用於字符串的方法: 文檔

"MyString".own_methods.sort

我用它來發現關於對象的新穎有趣的事情,不然我可能不知道存在。


#5樓

就像提到的@endeR同樣,若是要考慮國際化,那麼unicode_utils gem就足夠了。

$ gem install unicode_utils
$ irb
> require 'unicode_utils'
=> true
> UnicodeUtils.downcase("FEN BİLİMLERİ", :tr)
=> "fen bilimleri"

Ruby 2.4中的字符串操做如今對Unicode敏感。

相關文章
相關標籤/搜索