Search code examples
rubystringcharacterunique

Find if all letters in a string are unique


I need to know if all letters in a string are unique. For a string to be unique, a letter can only appear once. If all letters in a string are distinct, the string is unique. If one letter appears multiple times, the string is not unique.

"Cwm fjord veg balks nth pyx quiz."
# => All 26 letters are used only once. This is unique

"This is a string"
# => Not unique, i and s are used more than once

"two"
# => unique, each letter is shown only once

I tried writing a function that determines whether or not a string is unique.

def unique_characters(string)
  for i in ('a'..'z')
  if string.count(i) > 1
    puts "This string is unique"
  else
    puts "This string is not unique"
  end
end

unique_characters("String")

I receive the output

"This string is unique" 26 times.

Edit:

I would like to humbly apologize for including an incorrect example in my OP. I did some research, trying to find pangrams, and assumed that they would only contain 26 letters. I would also like to thank you guys for pointing out my error. After that, I went on wikipedia to find a perfect pangram (I wrongly thought the others were perfect).

Here is the link for reference purposes

http://en.wikipedia.org/wiki/List_of_pangrams#Perfect_pangrams_in_English_.2826_letters.29

Once again, my apologies.


Solution

  • s = "The quick brown fox jumps over the lazy dog."
    .downcase
    ("a".."z").all?{|c| s.count(c) <= 1}
    # => false
    

    Another way to do it is:

    s = "The quick brown fox jumps over the lazy dog."
    (s.downcase !~ /([a-z]).*\1/)
    # => false