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

孤者浪人 提交于 2019-12-01 10:38:31

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.

Sounds like you just need to convert to uppercase and don't need to bother with the if lowercase check at all, since applying #upcase to something that is already uppercase won't effect it.

For a single string you can use start_with? method as well.

user_input = gets.chomp

if user_input.start_with?(user_input.downcase)
    user_input.upcase!
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!