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

后端 未结 11 945
梦如初夏
梦如初夏 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:27

    You can find strings method like "strings".methods You can define string as upcase, downcase, titleize. For Example,

    "hii".downcase
    "hii".titleize
    "hii".upcase
    
    0 讨论(0)
  • 2020-12-07 07:28

    Since Ruby 2.4 there is a built in full Unicode case mapping. Source: https://stackoverflow.com/a/38016153/888294. See Ruby 2.4.0 documentation for details: https://ruby-doc.org/core-2.4.0/String.html#method-i-downcase

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-07 07:32

    ... and the uppercase is:

    "Awesome String".upcase
    => "AWESOME STRING"
    
    0 讨论(0)
  • 2020-12-07 07:32

    The Rails Active Support gem provides upcase, downcase, swapcase,capitalize, etc. methods with internationalization support:

    gem install activesupport
    irb -ractive_support/core_ext/string
    "STRING  ÁÂÃÀÇÉÊÍÓÔÕÚ".mb_chars.downcase.to_s
     => "string  áâãàçéêíóôõú"
    "string  áâãàçéêíóôõú".mb_chars.upcase.to_s
    => "STRING  ÁÂÃÀÇÉÊÍÓÔÕÚ"
    
    0 讨论(0)
提交回复
热议问题