How to convert a string to lower or upper case in Ruby

后端 未结 11 936
梦如初夏
梦如初夏 2020-12-07 07:00

How do I take a string and convert it to lower or upper case in Ruby?

11条回答
  •  时光取名叫无心
    2020-12-07 07:31

    Ruby has a few methods for changing the case of strings. To convert to lowercase, use downcase:

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

    Similarly, upcase capitalizes every letter and capitalize capitalizes the first letter of the string but lowercases the rest:

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

    If you want to modify a string in place, you can add an exclamation point to any of those methods:

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

    Refer to the documentation for String for more information.

提交回复
热议问题