how to write a program that getting this str where str = "\"five quacking zephyrs jolt my wax bed.\"", confirms that it is a pangram? in ruby

To check if a string is a pangram, you can use the following steps in Ruby:

  1. Start by removing all the non-alphabetic characters from the input string. In this case, we will remove the double quotes and backslashes.
  2. Convert the remaining string to lowercase to make the comparison case-insensitive.
  3. Create a Set of alphabets from 'a' to 'z'.
  4. Iterate over each character in the cleaned lowercase string.
  5. If the character is an alphabet, remove it from the Set.
  6. Finally, check if the Set is empty. If it is empty, then the input string is a pangram.

Here's the Ruby code that implements the above steps:

main.rb
require 'set'

def pangram?(str)
  # Remove non-alphabetic characters and convert to lowercase
  cleaned_str = str.gsub(/[^A-Za-z]/, "").downcase
  
  # Create a set of alphabets from 'a' to 'z'
  alphabet_set = Set.new('a'..'z')
  
  # Iterate over each character in the cleaned lowercase string
  cleaned_str.each_char do |char|
    # Remove the character from the set if it is an alphabet
    alphabet_set.delete(char)
    
    # Break the loop if the set becomes empty
    break if alphabet_set.empty?
  end
  
  # Check if the set is empty
  alphabet_set.empty?
end

str = "\"five quacking zephyrs jolt my wax bed.\""
puts pangram?(str) # Output: true
657 chars
25 lines

In this code, the pangram? method takes a string as input and returns a boolean value indicating whether it is a pangram or not. We use the gsub method to remove non-alphabetic characters, downcase method to convert the string to lowercase, and Set to store the remaining alphabets. Finally, we iterate over the characters in the cleaned lowercase string and remove them from the set. If the set becomes empty, we break the loop and return true, otherwise, we return false.

The output of the above code will be true, indicating that the input string is indeed a pangram.

related categories

gistlibby LogSnag