In ruby how do you tell if a string input is in uppercase or lowercase?

后端 未结 3 1488
后悔当初
后悔当初 2021-01-13 06:18

I am trying to write a program that when a single letter is inputted, if it\'s in uppercase, leave it in uppercase and return it, and if it\'s in lowercase, then convert to

3条回答
  •  感动是毒
    2021-01-13 07:05

    Just convert the string to upper case and compare it with the original

    string == string.upcase
    

    or for lowercase

    string == string.downcase
    

     

    Edit: as mentioned in the comments the solution above works with English letters only. If you need an international solution instead use

    def upcase?(string)
        !string[/[[:lower:]]/]
    end
    

    which uses a regular expressions to scan the string for lowercase letters and the negates the finding to tell whether the string is all uppercase.

提交回复
热议问题