Created
February 19, 2012 15:29
-
-
Save marcinwyszynski/1864315 to your computer and use it in GitHub Desktop.
Hash::reverse and Array::summarize
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
require 'test/unit' | |
Hash::class_eval do | |
# Flip the Hash so that former keys become values and | |
# former values become keys. The difference however is | |
# that if one value is assigned to multiple keys, then | |
# in the reversed Hash you get an array of values under | |
# that key. | |
def reverse | |
new_hash = {} | |
self.each do |key,val| | |
if new_hash.has_key?(val) | |
new_hash[val].push(key) | |
else | |
new_hash[val] = [key] | |
end | |
end | |
return new_hash | |
end | |
end | |
Array::class_eval do | |
# Count occurrences of elements in an Array so that the | |
# result is a Hash with unique elements as keys and their | |
# respective frequencies as values. | |
def summarize | |
hash = {} | |
self.each do |el| | |
if hash.has_key?(el) | |
hash[el] += 1 | |
else | |
hash[el] = 1 | |
end | |
end | |
return hash | |
end | |
end | |
class HashReverseTest < Test::Unit::TestCase | |
def setup | |
@hash = { 'a' => 1, 'b' => 1 } | |
end | |
def test_invert | |
result = { 1 => 'b' } | |
assert_equal(result, @hash.invert) | |
end | |
def test_reverse | |
result = { 1 => ['a', 'b'] } | |
assert_equal(result, @hash.reverse) | |
end | |
end | |
class ArraySummarizeTest < Test::Unit::TestCase | |
def setup | |
@array = [1,1,1,2,2,3] | |
end | |
def test_summarize | |
expected_result = { 1 => 3, 2 => 2, 3 => 1 } | |
assert_equal @array.summarize, expected_result | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment