give a regex-based isogram checker in ruby in ruby

To create a regex-based isogram checker in Ruby, you can use regex to match and identify any repeated characters in a given string. Here's an example code snippet:

main.rb
def is_isogram?(word)
  # Convert the word to lowercase and remove any non-alphabetic characters
  clean_word = word.downcase.gsub(/[^a-z]/, '')
  
  # Use regex to check if there are any repeated characters
  repeated_chars = clean_word.scan(/(.).*\1/)
  
  # If the regex finds any repeated characters, it's not an isogram
  repeated_chars.empty?
end

# Example usage
word1 = "programming"
word2 = "eleven"

puts is_isogram?(word1)  # Output: false
puts is_isogram?(word2)  # Output: true
491 chars
18 lines

In the example above, the is_isogram? method takes a word as input and converts it to lowercase. It then removes any non-alphabetic characters using the gsub method. The scan method with a regex pattern /(.).*\1/ is used to find any repeated characters in the cleaned word. If no repeated characters are found, the method returns true (i.e., the word is an isogram). Otherwise, it returns false.

Please note that this regex-based approach assumes that the input only contains alphabetic characters. If you want to handle non-alphabetic characters as well, you can modify the regex pattern accordingly.

related categories

gistlibby LogSnag