Skip to content

Instantly share code, notes, and snippets.

@phildionne
Created October 5, 2012 21:45
Show Gist options
  • Save phildionne/3842602 to your computer and use it in GitHub Desktop.
Save phildionne/3842602 to your computer and use it in GitHub Desktop.
# Anagram
def combine_anagrams(words)
h = Hash.new
words.each do |word|
(h[word.downcase.chars.sort.join] ||= []) << word
end
h.values
end
words = ['Cars', 'for', 'potatoes', 'rAcs', 'four', 'scar', 'crEams', 'scream']
combine_anagrams(words)
########################################
# Custom attr_accessor with attribute value recording
class Class
def attr_accessor_with_history(attr_name)
attr_name = attr_name.id2name
attr_reader attr_name
attr_reader attr_name+"_history"
class_eval %Q[
def #{attr_name}=(arg)
@#{attr_name} = arg
(@#{attr_name}_history ||= [nil]) << arg
end
]
end
end
class Foo
attr_accessor_with_history :bar
end
f = Foo.new
f.bar = 3
f.bar = :wowzo
f.bar = 'boo!'
f.bar_history # => [nil, 3, :wowzo, 'boo!']
########################################
# Palindrome?
def palindrome?(str)
sanitized_string = str.gsub(/\W/, "").downcase
sanitized_string == sanitized_string.reverse
end
palindrome?("A man, a plan, a canal -- Panama")
# Count ALL the words!
def count_words(str)
sanitized_words = []
word_occurences = {}
str.gsub(/\w+/) {|word| sanitized_words << word.downcase}
sanitized_words.each do |word|
word_occurences[word] = (word_occurences[word] || 0) + 1
end
word_occurences
end
count_words("A man, a plan, a canal -- Panama")
count_words "Doo bee doo bee doo"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment