Skip to content

Instantly share code, notes, and snippets.

@Sephi-Chan
Created May 26, 2011 11:11
Show Gist options
  • Save Sephi-Chan/992939 to your computer and use it in GitHub Desktop.
Save Sephi-Chan/992939 to your computer and use it in GitHub Desktop.
class Array
# Count occurences of values in the array.
# Return it as a hash.
#
# [1, 1, "foo", :bar, 1, :bar].count_occurrences # => {1 => 3, "foo" => 1, :bar => 2}
def count_occurrences
h = self.group_by { |x| x }
Hash[h.map { |k, v| [ k, v.length ] } ]
end
end
class ArrayCountOccurrencesTests < Test::Unit::TestCase
def test_count_occurrences_with_scalar
source = [ 1, 1, "foo", :bar, 1, :bar ]
result = { 1 => 3, "foo" => 1, :bar => 2 }
assert_equal result, source.count_occurrences
end
def test_count_occurrences_with_hash
source = [ { "foo" => "bar" }, { "foo" => "bar" }, { :bar => :foo } ]
result = { { "foo" => "bar" } => 2, { :bar => :foo } => 1 }
assert_equal result, source.count_occurrences
end
def test_count_occurrences_with_hash_and_arrays
source = [ { "foo" => "bar" }, { "foo" => "bar" }, { :bar => :foo }, [ 1, 2, 3 ], [ 1, 2, 3 ], [ 4 ] ]
result = { { "foo" => "bar" } => 2, { :bar => :foo } => 1, [ 1, 2, 3 ] => 2, [ 4 ] => 1 }
assert_equal result, source.count_occurrences
end
def test_count_occurrences_with_everything
source = [ 8, { "foo" => "bar" }, { "foo" => "bar" }, 8, { :bar => :foo }, [ 1, 2, 3 ], [ 1, 2, 3 ], [ 4 ], :foo ]
result = { { "foo" => "bar" } => 2, { :bar => :foo } => 1, [ 1, 2, 3 ] => 2, [ 4 ] => 1, 8 => 2, :foo => 1 }
assert_equal result, source.count_occurrences
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment