shortest possible isogram checker that can also scan for hyphens, dahses and white space? in ruby

To create a shortest possible isogram checker in Ruby that also scans for hyphens, dashes, and white space, you can use the following code:

main.rb
def is_isogram?(input)
  normalized_input = input.gsub(/[-—\s]/, '').downcase
  normalized_input.chars.uniq.length == normalized_input.length
end
146 chars
5 lines

Explanation:

  • The is_isogram? method takes an input string as a parameter.
  • gsub(/[-—\s]/, '') replaces all hyphens, dashes, and white space in the input string with an empty string (''), effectively removing them from the string.
  • downcase converts the string to lowercase to ignore case sensitivity.
  • chars converts the string into an array of characters.
  • uniq removes the duplicates from the array of characters.
  • length returns the length of the array after removing duplicates.
  • The method then checks if the length of the array of unique characters is equal to the length of the normalized input string. If they are equal, it means that each character occurs only once, making it an isogram.

Usage:

main.rb
puts is_isogram?('programming')  #=> true
puts is_isogram?('Ruby')         #=> true
puts is_isogram?('Hello World')   #=> false
puts is_isogram?('race-car')      #=> false
puts is_isogram?('qwerty')        #=> true
215 chars
6 lines

In the above example, "programming" and "Ruby" are isograms, while "Hello World" and "race-car" are not due to the repeated character 'l' and 'r' respectively. The last example "qwerty" is also an isogram since it doesn't have any repeating characters after removing hyphens, dashes, and white space.

related categories

gistlibby LogSnag