5

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?

test
  • 51
  • 1
  • 2
  • possible duplicate of [How can I check a word is already all uppercase in Ruby?](http://stackoverflow.com/questions/8529595/how-can-i-check-a-word-is-already-all-uppercase-in-ruby) – philant May 29 '15 at 09:14

3 Answers3

11

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.

akuhn
  • 27,477
  • 2
  • 76
  • 91
  • 2
    [`upcase`](http://ruby-doc.org/core-1.9.3/String.html#method-i-upcase) and [`downcase`](http://ruby-doc.org/core-1.9.3/String.html#method-i-downcase) come with an important caveat: they only work with ASCII. – mu is too short Nov 25 '12 at 02:26
  • Really? #upcase and #downcase only work for ASCII only? Sounds like a bug to me, given Ruby's new "encoded" world view. Do you have a snippet of code to demonstrate this? – trans Nov 25 '12 at 11:41
  • According to the documentation, case mapping methods were limited to ASCII as of Ruby 1.9.3, but became more broadly compatible some time before Ruby 3.1.2; see https://ruby-doc.org/core-3.1.2/doc/case_mapping_rdoc.html – ShadSterling Jul 06 '22 at 22:34
2

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.

trans
  • 1,411
  • 1
  • 13
  • 13
1

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
ark1980
  • 295
  • 4
  • 8