Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 uppercase. How do I write this to be able to tell if the string is originally in uppercase or lowercase?

like image 800
test Avatar asked Nov 25 '12 02:11

test


3 Answers

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.

like image 177
akuhn Avatar answered Sep 20 '22 03:09

akuhn


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.

like image 38
trans Avatar answered Sep 21 '22 03:09

trans


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
like image 45
ark1980 Avatar answered Sep 21 '22 03:09

ark1980