Created
June 14, 2012 16:49
-
-
Save pwightman/2931441 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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