0

I have seen a way of testing whether a string is a pangram -- a sentence containing every letter of the alphabet -- but I didn't quite understand it. I want to know why my way isn't working.

def is_pangram(string)

  alpha = ("a".."z").to_a
  i = 0
  while i < string.length
    if string.downcase[i] == alpha.any? 
        alpha.delete(string.downcase[i])
    end
    i += 1
  end

  if alpha.length > 0
    puts "This string is not a pangram"
  else
    puts "This string is a pangram"
  end

  puts alpha.length
  puts alpha
end

is_pangram("The quick brown fox jumps over the lazy dog")
Jochem Schulenklopper
  • 6,452
  • 4
  • 44
  • 62
Hn Nm
  • 19
  • 6
  • 3
    The issue is here: `string.downcase[i] == alpha.any?` LHO is a letter, while `alpha.any?` returns boolean denoting whether the array is not empty. This condition never meets. It should be `alpha.include?(string.downcase[i])`. – Aleksei Matiushkin Oct 10 '18 at 13:47
  • @Aleksei, what have you done? Surely you must recognize that my past references to "mudsie" will now be met with blank stares! (Readers: until recently Aleksei went by the SO user name "mudasobwa".) – Cary Swoveland Oct 11 '18 at 07:21
  • 1
    @Cary I would appreciate if you’ll continue reference me as mudsie, I definitely love it. – Aleksei Matiushkin Oct 11 '18 at 07:22

3 Answers3

1

Aleksei has already answered the question... here's a slightly cleaner way of doing it.

def is_pangram(string)

  alpha = ("a".."z").to_a
  string.downcase.split("").each do |i|
    alpha.delete(i) if alpha.include?(i)
  end

  if alpha.empty?
    puts "This string is a pangram"
  else
    puts "This string is not a pangram"
  end

  puts alpha.length
  puts alpha
end

is_pangram("The quick brown fox jumps over the lazy dog")
Joseph Cho
  • 4,033
  • 4
  • 26
  • 33
1

How about the following?

def is_pangram?(str)
  str.downcase.scan(/[a-z]/).uniq.size == 26
end

is_pangram? "The quick brown dog jumps over the lazy fox."
  #=> true
is_pangram? "The quick brown dog jumps over the wary fox."
  #=> false
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
0

but I didn't quite understand it

The (intended) algorithm builds an array containing all the (26) letters of the alphabet. Then it processes the string, character by character, removing that character from the first array (if it is still in there). After that, it simply tests whether the first array is empty. If so, the characters in the string have led to removal of all the characters in the array, and the string is thus a pangram. If not, some character was 'missing' in the string, and that character is still in the array.

Jochem Schulenklopper
  • 6,452
  • 4
  • 44
  • 62