Skip to content

Instantly share code, notes, and snippets.

@pwightman
Created June 14, 2012 16:49
Show Gist options
  • Save pwightman/2931441 to your computer and use it in GitHub Desktop.
Save pwightman/2931441 to your computer and use it in GitHub Desktop.
def palindrome? str
str.downcase!
# gsub stands for "global substitution" and replaces all occurrences
# of the matching regex with the given string. Here, we want all "non-word"
# characters to be removed from the string
str.gsub! /[\W]/, ""
# If the forward and backward versions are the same, it's a palindrome
str == str.reverse
end
puts palindrome?("hello world")
puts palindrome?("A man, a plan, a canal -- Panama")
def count_words str
hash = Hash.new(0)
str.scan(/\w+/).each do |match|
hash[match.downcase] += 1
end
hash
end
puts count_words("hello world")
puts count_words("A man, a plan, a canal -- Panama")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment