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

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

    Like @endeR mentioned, if internationalization is a concern, the unicode_utils gem is more than adequate.

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

    String manipulations in Ruby 2.4 are now unicode-sensitive.

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

    In combination with try method, to support nil value:

    'string'.try(:upcase)
    'string'.try(:capitalize)
    'string'.try(:titleize)
    
    0 讨论(0)
  • 2020-12-07 07:15

    The .swapcase method transforms the uppercase latters in a string to lowercase and the lowercase letters to uppercase.

    'TESTING'.swapcase #=> testing
    'testing'.swapcase #=> TESTING
    
    0 讨论(0)
  • 2020-12-07 07:21

    Won't work for every, but this just saved me a bunch of time. I just had the problem with a CSV returning "TRUE or "FALSE" so I just added VALUE.to_s.downcase == "true" which will return the boolean true if the value is "TRUE" and false if the value is "FALSE", but will still work for the boolean true and false.

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

    You can find out all the methods available on a String by opening irb and running:

    "MyString".methods.sort
    

    And for a list of the methods available for strings in particular:

    "MyString".own_methods.sort
    

    I use this to find out new and interesting things about objects which I might not otherwise have known existed.

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

    The ruby downcase method returns a string with its uppercase letters replaced by lowercase letters.

    "string".downcase
    

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

    0 讨论(0)
提交回复
热议问题